Console Learner — An interactive JavaScript course.


4.4 More of This

>>>
var obj = {
    a : 13,
    b: 42,
    total: function() { return this.a + this.b }
}


  
>>>
obj.total()
55
Any object can have function properties, allowing them to be used as methods. But remember that this is bound at call-time.
>>>
obj.total.apply({ a: 1, b: 2 })
3
The first argument to apply() and call() binds this to a specified value. Methods can therefore be called on another object, as long as it is similar enough.
>>>
var total = obj.total;


  
>>>
total()
NaN
But the call-time binding of this also means that the object context can be lost. This typically happens when passing a function reference to an event handler, setTimeout() or similar.
>>>
var boundMethod = obj.total.bind(obj);


  
>>>
boundMethod()
55
The built-in function bind() method can be used to create a function where this is bound to a specific object.
>>>
boundMethod.apply({ something: 'else' })
55
The bound function will keep the object reference intact, ignoring the object context used in the function call.
>>>
obj.toString = () => this.a + ", " + this.b;


  
>>>
obj.toString()
"undefined, undefined"
Arrow functions are different, as this is instead bound on creation. This is useful for helper functions inside methods, but here it caused toString() to be incorrect.
>>>

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.