O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.5. What Is 'this'

If you're used to using languages like C++, C#, or Java™, then you'll probably be used to the idea that inside a method, this refers to the object that the method belongs to. It's very different in JavaScript, as methods do not belong to objects. Instead, this refers to the object that a method is called on - that may change from object to object.

var fn = function()
{
       return this.x;
}

var widget = new Widget();
var person = new Person();

widget.getX = fn;
person.returnX = fn;

widget.getX(); // here this is the widget.
person.returnX(); // here this is the person.

This can be confusing when we are using event handlers.

. Consider a counting class:

function Count()
{
       this.count = 0;
}

Count.prototype.add = function() { this.count++;}

Now assume we have a link on an HTML page:

<a href='#' id = 'a0'>count</a>

If we were to wire up an event handler like:

document.getElementById('a0').onClick = myCount.add;

Then we would not increment the count object, but instead attempt to increment a property called count on the a object. This is because the above code actually gets called on the a object, not the Count object. To make sure it gets called on the count object, we must instead use a closure.

 document.getElementById('a0').onClick = function() {myCount.add();}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required