Console Learner — An interactive JavaScript course.


4.3 This

>>>
this
[object Window]
The this keyword provides access to the current object context. In the outermost scope, it points to the window object in web browsers.
>>>
function MyObject(val) {
    this.a = val;
    this.b = 'test';
}

  
Inside constructor functions, this references the new object instance created.
>>>
var obj = new MyObject(123);


  
>>>
obj
{ "a": 123, "b": "test" }
Using this, the constructor function can initialize and modify the new instance.
>>>
function example() {
    return 'a = ' + this.a + ', b = ' + this.b;
}


  
>>>
example()
"a = undefined, b = undefined"
Inside normal functions, using this is mostly pointless (or even erroneous).
>>>
obj.toString = example;

  
But if the function is bound to an object property, it can be called as a method of the object.
>>>
obj.toString()
"a = 123, b = test"
When functions are called as object methods, this is automatically bound to the object in question. This binding happens at call-time.
>>>
'str: ' + obj
"str: a = 123, b = test"
Also note that toString() is the special method used when coercing an object to a string.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.