I’m working with the source code for VirtualJoystick and I’m confused about the method binding:
__bind = function(fn, me){return function(){return fn.apply(me, arguments); }; };
this._$onTouchStart = __bind(this._onTouchStart , this);
Next it creates an eventListener:
this._container.addEventListener( 'touchstart' , this._$onTouchStart , false );
which refers to a later-defined method:
VirtualJoystick.prototype._onTouchStart = function(event)
{
if( event.touches.length != 1 ) return;
event.preventDefault();
var x = event.touches[ 0 ].pageX;
var y = event.touches[ 0 ].pageY;
return this._onDown(x, y)
}
This seems convoluted to me. Why bind the alias before creating the eventListener?
Because otherwise it would be called with a
thisequal to the global object (or tonullin strict mode).The same would happen if you did
In general any time you “alias” a method, i.e. don’t call it directly as a method (with the appropriate object behind the dot), you lose the
thiscontext for it. Passing a method as a parameter does exactly this kind of aliasing, which is why it’s necessary foraddEventListener.__bind, or its standard version Function.prototype.bind, gets around this, making sure that the function is called with thethispointer it expects. It creates a version of the function that is always called with the boundthis, instead of the contextually-determined version.