Understanding “this” keyword and how to play with it is a very important thing in JavaScript. In general, “this” is referencing to current instance, similar with C#. However, I will try to illustrate in some example, what “this” means.

“this” referencing to window object

This is the classical JavaScript example, when “this” keyword is referencing to window object.

        var name = 'Popescu';       

        function randomFunction() {
            alert(this.name);
        }

        // Will alert Popescu
        randomFunction();

To understand this example, you need to know that window is object, name is a property of window and randomMethod is a method of it. As name and property are properties of the same object, variable “name”, referencing inside the method using “this.name”, represents the output of the alert.

Specify “this” reference using call and apply

Classical example above is not necessary to be always true. A JavaScript developer can specify what “this” should reference by using call and apply. Let’s take a look on below portion of the code.

  var name = 'Popescu';

var context = new Object();
context.name = 'Popescu Andrei Vlad';

function randomFunction() {
   alert(this.name);
}

// Will alert Popescu Andrei Vlad
randomFunction.call(context);
randomFunction.apply(context);

This time “this” is referencing to context object. And if you are a fan of Microsoft Ajax, you can write it even more beautiful.

var name = 'Popescu';

var context = new Object();
context.name = 'Popescu Andrei Vlad';

function randomFunction() {
    alert(this.name);
}

// Will alert Popescu Andrei Vlad
Function.createDelegate(context, randomFunction)();

“this” in a XMLHttpRequest context

Using “this” in a XmlHttpRequest context can create confusion for a beginner. For example, code below will alert undefined.

var name = 'Popescu';

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'url', true);
xmlHttp.send(null);

xmlHttp.onreadystatechange = function () {
    alert(this.name);
}

This is because, in our code “this” is not referencing any more to window object. It is a reference to XMLHttpRequest object. So, alerting value of this.readyState will work.

Advertisements