Monday, August 27th, 2007
A Quick Lesson in Binding & Execution Scope
One of the reasons that I love reading Justin Palmer’s blog is that he injects humor into his posts making normal technical babble that much more interesting.
In Justin’s post, Understanding Scope and Binding in JavaScript, he gives a good rundown on how scope is affected when binding objects:
Binding and Events
In PAJ™ (Plain Ass JavaScript) , this inside a callback is actually the element which invoked the event, so it’s fairly easy to do the code like below.
var ninja = document.getElementById(’ninja’);
ninja.addEventListener(’click’, function () {
alert(this.tagName);
}, false);However, in Prototype this points to the window object inside a callback so we need to use bind in order to bind it to the object the method belongs to.
var Ninja = Class.create();
Ninja.prototype = {
…addObservers: function() {
$(’item’).observe(’click’, this.kickSomeone.bindAsEventListener(this));
},kickSomeone: function(event) {
// Works because `this` is the Ninja instance
// Without binding it would be the window
this.someOtherMove();
}…
}
I had to laugh when I saw his “This is SPAARRTTAAAA!” example! ;)












Leave a comment