javascript interactive

JavaScript Interactive — a console crash course


4.3 This

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
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 being 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.
>>>
obj.toString = example;

  
But if the function is bound to an object property, it can be used 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.
>>>

Index 1 2 3 4 5 6 7 8