What is this?

JavaScript has a keyword this, whose value depends on the execution context. It is always an object (and never an immutable, such as a number).

Test code

TEST('return_this', function()
{
    var return_this = function(){
        return this;
    };

    var default_this = return_this();
    assert( default_this.telltail === 'global' );

    var obj = {};
    obj.return_this = return_this;
    assert( obj.return_this === return_this );

    assert( obj.return_this() === obj );
    assert( obj['return_this']() === obj );

    assert( return_this.call(obj) === obj );
    assert( return_this.apply(obj) === obj );

    assert( return_this.call(undefined).telltail === 'global' );
    assert( return_this.apply(undefined).telltail === 'global' );

});

Discussion

The function return_this is a convenient way of getting of getting hold of the object that is the value of this. The code that follows shows:

  1. The default value of this is the global object.
  2. When return_this is called as either a method (i.e. an attribute that is a function) or item of obj then this is obj itself.
  3. That the call and apply methods of a function allow us to set the value of this within a particular execution of the function.
  4. If we pass undefined to function call or apply then we get the global object as this.

Explanation

Throughout the execution of JavaScript code, the identifier this has a value, which is an object (and not an immutable value). The value of this depends on how the JavaScript interpreter got to be executing the code.

  1. At the command line this is the global object.
  2. In a function this is the object from which the interpreter got the function.
  3. Because global variables are attributes of the global object, the rule for calling global variables as functions is a special case of the previous rule.

Here’s a helpful way to look at the situation. It is as if the interpreter maintains a this stack, which starts containing a single item, the global object. Each time an item access of an object is immediately followed by a function call, the object is added to the this stack, and removed at the end of the function call. For all other function calls the global object is added to the this stack.

During execution of a function the value of this is the element at the top of the this stack.

Finally, the function call and apply methods allow for a particular object to be placed at the top of the this stack before the function is called.

Exercises

  1. At the command-line try making an assignment to this. What happens?

  2. Try loading a JavaScript program that makes an assignment to this. What happens?

  3. For what values of value is the following true?

    return_this.apply(value) === value;
    
  4. Write a simple test that detects these values.