I’ve written before about how the this keyword is used in JavaScript and how problems can arise. This article deals specifically with how to use this without running into problems.

Lets say we have the following function:

function f() {
    this.data = "hello world";
    this.getData = function() {
        return this.data;
    };
}

If we call the getData() method from the f function object then all is well as this.data will refer to the data property of f. If we were to call the getData() function from another object then this will no longer point to the correct thing, we can get around this problem in a number of ways:

Using a closure

Rewriting f() like this would fix the problem so that we can always refer to the data property correctly

function f() {
    var self = this;
    this.data = "hello world";
    this.getData = function() {
        return self.data;
    };
}

The getData() function is now a closure, it has a reference to the self variable defined in the outer f() function and it will retain this reference for its lifetime, no matter where it is called from.

Using call() and apply()

JavaScript functions are objects, they are instances of the Function object. The Function object has two methods called apply() and call() that are handy for scoping function calls and controlling this; both functions do the same thing but have different parameter sets. Example usage:

function f() {
    this.data = "hello world";
    this.getData = function() {
        return this.data;
    };
}

var a = new f();
alert( a.getData() ); //prints "hello world"
var b = a.getData;
alert( b() ); //prints "undefined"

alert( c.call( a ) ); //prints "hello world"
alert( c.apply( a ) ); //prints "hello world"

The calls to apply() and call() look odd but there’s no magic here. When we pass a as the parameter to them both we are saying, “call function c in the scope of a; in other words, set this to a”. The apply() function has an optional 2nd parameter, which is an array of parameters to pass to the function.