Monday, August 27th, 2007

A Quick Lesson in Binding & Execution Scope

Category: JavaScript

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 () {
}, 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


I had to laugh when I saw his “This is SPAARRTTAAAA!” example! ;)

Posted by Rey Bango at 6:00 am
Comment here

3.2 rating from 21 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.