Demystifying “this” in JavaScript


If you have worked with Object Oriented languages in the past and then moving to JavaScript, one of the first thing that you need to do is to understand the usage of “this” operator.

this” in other languages that are class-based like C++, Java & C# points to the object that holds the current instance of the class. JavaScript too provides a similar concept using the same this keyword, but beware! – there is a significant difference. In JavaScript functions are first-class objects and they aren’t part of anything else. So the object declared by this (termed as function context) is not determined by how the function is declared but by how it’s invoked. It means the same function can have different contexts depending on how it’s called.

This can be explained by a simple example:

 <script type="text/javascript">

        window.firstName = "WindowFirstName";
        window.lastName = "WindowLastName";

       function fullName(){
            return this.firstName + " " + this.lastName;
        }

        var person1 = new Object();
        person1.firstName = "Steve";
        person1.lastName = "Jobs";
        person1.fullName = fullName;

        var person2 = new Object();
        person2.firstName = "Nish";
        person2.lastName = "Anil";
        person2.fullName = fullName;

       alert(fullName());
       alert(person1.fullName());
       alert(fullName.call(person2));

    </script>

 

In the above code sample notice the function fullName() which returns firstName and lastName and how they access the properties using this operator.  Each alert defined here provides a different output and explains the function context in its true sense! Let’s explore each of the outputs –

alert(fullName())

Here fullName() is accessed as top-level function and remember the top-level functions are properties of window so the function context will be the window itself. In this execution the code will look for firstName and lastName in the window object which is actually set on top with values WindowFirstName & WindowLastName! So the output will be:

image

alert(person1.fullName())

 fullName is a property that is defined within persorn1 object which internally holds the reference of the function fullName. So in this case the function context will be of the calling function person2 and hence it returns values of firstName & lastName defined within the object.

image

alert(fullName.call(person2))

In JavaScript you can explicitly control what’s used as the function context by invoking a function via the Function methods call() &apply().

In this case we are invoking the function using the call() method and specifying the first parameter as it’s function context. person2 is passed to the call() method which set’s the function context as person2.  Hence the output:

image

Hope this post explained “this” in JavaScript and why you should care! You can read more on using this at the Mozilla developer Network documentation.

-Nish

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s