javascript interactive

JavaScript Interactive — a console crash course


4.4 More of 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.
>>>
var obj = {
    a : 13,
    b: 42,
    print: function() { print(this); }
}


  
>>>
obj.print();

  
Any object can have function properties, allowing them to be used as methods. But remember that this is bound at call-time.
>>>
obj.print.apply({ something: 'else' });

  
Function calls with apply() or call() use the first argument as the bound this object. This makes it possible to reuse a method for any object, as long as it is similar enough to work properly.
>>>
var printMethod = obj.print;

  
>>>
printMethod();

  
But the call-time binding of this also means that the object context can be lost when function references are passed along. This typically happens when using event handlers, setTimeout() or similar.
>>>
var boundMethod = obj.print.bind(obj);

  
>>>
boundMethod();

  
The built-in bind() method can be used to create a new wrapper-function where this is bound to a specific object.
>>>
boundMethod.apply({ something: 'else' });

  
The wrapper-function will keep the object reference intact, ignoring the object context used in the function call.
>>>
setTimeout(boundMethod, 0);

  
The wrapper-function can therefore be used in event handlers and where the object context would otherwise be lost.
>>>

Index 1 2 3 4 5 6 7 8