What is this in JavaScript

posted on 4/17/2015 4:53 AM by Eric Butler


If you come from a C++/C# background, you'll most likely have a good grasp on what the 'this' keyword is. But enter the JavaScript realm, and 'this' takes a whole new twist.

What is this?

In most object-oriented programming languages, 'this' refers to the object in which you are stuffing your fields, properties, and methods. For example, you create a class called Car, and you add a method called Drive(). From within a method, if you access the 'this' keyword/object, you are referencing the instance of your Car class, and that never changes. Here is an example:


class Car {

    public string Color {get; set;}

    public void Drive(){
        //access the Color property
        this.Color = "red";
        //'this' refers to an instance of our Car class. When Drive is called,
        //the Color property is set.
    }

}

That's a really simplistic example. The 'this' keyword is used to get a reference to the Car object, and no matter where you are in that code, or regardless of how that method is invoked, 'this' will ALWAYS be the Car object reference.

So what about JavaScript?

JavaScript is considered an Object-Oriented language... literally. Everything in JavaScript is considered an object, even functions. So, how exactly does 'this' work in JavaScript? In a lot of cases, 'this' works much in the same way as C++ and C#. For example:


function Car() {

    this.color = 'red';

    this.drive = function () {
        //access the Color property
        alert(this.color);

    }
}

Ok, here, the same thing applies, 'this' is the reference to our Car instance. When we call drive(), we can access that instance and display the car color.

So what's the catch?

The 'this' keyword, does not always refer to the object you think it does. In some cases, this can refer to a completely different object. Here's an example of using 'this' inside a jQuery event handler:


(function() {

    this.myVar = 123;
    
    $('#button').click(function(){
        //show the value
        alert(this.myVar);
    });

})();

If you guessed that the alert would output the value '123', you would be mistaken. In any other language, sure, it would have, but in JavaScript, 'this' can be manipulated to be whatever you want, or in this case, whatever the developers of jQuery want. The actual result is:

Ok, why?

When a function is called, normally 'this' would refer to the object, but in some cases, it can be changed to something else. If we call a function using the "apply" method, we can pass an object as a parameter, and then suddenly, 'this' refers to the object we passed. In the case of our jQuery example above, 'this' actually refers to the button element you clicked on! If we did this instead:


alert(this.id);

we would see:

The 'apply' method invokes the function we want to call, but changes the 'this' keyword to refer to the object we want:


(function () {
    $('#button').click(function () {
        //show the value
        myFunction.apply(123);
    });

    function myFunction() {
        alert(this);
    }
})();

myFunction() is called using apply, and 123 is passed as the object. In our function, we use alert() to show the value of 'this':

If you have a function that accepts parameters, you can pass them like so:


(function () {
    $('#button').click(function () {
        //show the value
        myFunction.apply(123, [1,2]);
    });

    function myFunction(param1, param2) {
        alert(this + ' ' + param1 + ' ' + param2);
    }
})();

We can bend 'this' to do our bidding! Imagine all the possibilities! Well, imagine the headache. In our jQuery example where we wanted to show the value 'myVar', you might be wondering, "How do I access properties in my object if 'this' could be anything? The simplest, and most widely used solution, is to create a private variable, and store the reference to 'this'. Most likely, you will see something along the lines of:


(function() {
    var _self = this;
    this.myVar = 123;
    
    $('#button').click(function(){
        //show the value
        alert(_self.myVar);
    });

})();

This is the quickest, most painless way to deal with the uncertainty of 'this'. Within your code, if you always refer to '_self' you'll have no trouble accessing your object's properties.

The ability to control what 'this' means in your code gives you powerful flexibility. You can create callbacks for loops, where each iteration calls the function with apply to set 'this' to the array element (like jQuery.each() does), and so on. If you would like to get your hands a bit dirty, check out an example I created on jsfiddle.net:

View Example



As a thank-you, please consider sending a small donation. You can contribute as much as you'd like.

Comments

Log in to leave a comment

Log In