On Javascript explicit binding and binding loss

Post date: Sep 07, 2014 4:18:29 AM

First of all, javascript requires explicit binding, i.e. explicit use of the this keyword when a method wants to access its member variables. This is because javascript is not built from the ground up to support traditional object-oriented inheritance [1]. Secondly, the javascript language allows functions to be treated as first-order values, i.e.

var fx = obj.method;

fx(arg);

When this happens, the new function is simply a reference to the original object method, which does not have binding to the object anymore. In [1], this is referred to as "binding loss". This can be fixed by the following common code pattern inside a class definition

var self = this;

which simply creates a reference to the original object and only use it later on. For more info on object-oriented programming in javascript, see [2].

[1] http://alistapart.com/article/getoutbindingsituations

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript