JavaScript Tutorial Newsletter Do you want to learn how to write code? This is an independent code programming tutorial website. All tutorials are written and distributed for free to whosoever wishes to sign up. There are no ads. Please support us by subscribing to LearnjQuery.org free tutorial updates newsletter.



Join other 5 subscribers

The "this" variable in JavaScript

Because jQuery is written in JavaScript and it is an elegant extension thereof, it is easy to forget that when we write jQuery code we are still writing JavaScript code.

One of the often misunderstood features of the JavaScript language is the this variable (which points to an object.) It's known for being elusive and difficult to understand because of its chameleon nature:

Ecma-262 International Specification on page 57, specifies the rules for the JavaScript language with regard to design of the this keyword:

The this keyword evaluates to the value of the current execution context.

The value stored in the this keyword changes based on the circumstance in which it is encountered.

In order to understand the different sides of the this variable the examples below will demonstrate its usage in most common situations. The scope of the JavaScript program is the most critical part. The scope inside of which the this variable is used determines the context in which it is used.

Therefore, when you think about working with the this variable first determine the scope in which it is used. In order to demonstrate what it is pointing to in different circumstances we can use the triple equals sign operator === (or strict comparison operator.) This way we can determine whether the this variable equals (or refers to) the same object.

Using the this variable in the global scope:

Let's type something directly into the JavaScript program in between <script></script> tags. We know that the window object exists within the global scope by default.

<script> if (this === window) alert("The object this refers to the global window object"); </script>

This will be true, and the alert will fire, confirming that the this object indeed refers to the global window object in the global scope.

Using the this variable in the scope of a named function:

function my_function() { if (this === window) alert("The object this is the same as the global window object"); }

Let's see what happens here. Again, the alert will fire. The variable this points to the window object. This may sound peculiar especially because we determined earlier that the this object changes its color like a chameleon, depending on where it is used. But inside a named function it still equals to the window object, even though it is no longer in the global scope, but that of a named function.

This is not useful in most circumstances. However, the function my_function is defined within the scope of the window object. The reason the this variable still refers to the window object (also known as the Global Object in JavaScript) inside a named function is because it refers to its parent. Truly, this makes sense now when we look at it that way.

In JavaScript a function that belongs to an object is called a method. The function my_function in this case is a method of the Global Object window, simply because we defined it within its scope. So, within a function the this object points to the parent object to which it belongs.

Knowing this, we can draw the following observation. Let's say we have a function a with a method b, and we can call the method b as follows using the dot operator:

a.b(); // variable this inside b points to a: the parent.

Within the function b the this variable will refer to the parent object a.

Using the this variable in the scope of a nameless (anonymous) function (also known as the callback function, in combination with an event):

Let's call the click method and add an anonymous callback function to it:

$("div#target").click( function() { if (this === window) // fails, jQuery does not refer to window object here alert("this === window"); if (this === $) // fails; the this variable does not point to the main jQuery object either alert("this === $"); if (this === document.getElementById('#target'); // correct alert("this === document.getElementById('#target')"); } );

Within an anonymous callback function attached to a jQuery event, we see that the this variable points to the raw JavaScript object representing the selected element. However, it is not the jQuery object itself. The jQuery methods will not work directly on the this variable in this scenario, unless we pass it to the jQuery object again:

$("div#target").click( function() { this.style.color = "red"; // make the clicked element red var divTarget = $(this); divTarget.css( { color: "blue" } ); // call additional jQuery methods on div#target but now using a jQuery method });

As seen in this example now we can call additional methods on the received this object within an anonymous callback function after passing it to the main $ object. So you have both references within such a function: one to the original raw JavaScript object (document.getElementById) and another to the same object as an jQuery instance.

Using the this variable in the scope of an object literal:

var objectLiteral = { a: "1", b: "2", c: this, d: function() { alert(this); } }; alert(objectLiteral.c); // displays [object Window]

Here, c equals the main Window object, because objectLiteral is stored within it (the global scope.)

Notice that we used this two times in the same object literal. However, the following example will demonstrate that they refer to two different things in practice.

In an Object Literal (the literal representation of a JavaScript object created using the brackets and not the new operator nor a function) the this variable still points to the window object because it is created within the scope of the global window object.

But what will happen if we try to access the second this object hidden inside the function d?

var objectLiteral = { a: "1", b: "2", c: this, d:function() { alert(this) } }; alert(objectLiteral.c); // [object Window] objectLiteral.d(); // [object Object]

As you can see, it now refers to object of type Object (not Window.) In JavaScript a custom object can be created, it is considered to be of type Object. In the same way as when a literal string (eg: "abs") is created it will be considered of type String (after primitive coercion.)

In the latter case objectLiteral.d executes the function d which is a method of the object pointed to by the Literal object variable. The same principle is at work.

In Conclusion

The this variable will point to its parent object. However, in the case of custom functionality such as seen in jQuery event callback functions, the this variable will refer to the raw JavaScript object that was selected using the jQuery CSS selectors. See also (jQuery CSS Selectors Part II).

In regular JavaScript chain of methods: em.en.oh.pe() the this variable within pe() points to the method oh (not the method em.) In other words the previous parent, not the original.

© 2014 Copyright LearnjQuery.org.