ES5 shim for binding functions is Javascript
Question
Below is a ES5 shim for JS binding.I dont understand self.apply in the bound function.
I know how to use apply method, but where is self pointing to in this case ? It it supposed to be a
function, but here self looks like an object.
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ), // self in this line is supposed
to // represent a function ?
args.concat( slice.call(arguments) ) );
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
Solution
Have in mind that in javascript almost everything is an object.
So you have it right there:
self = this
So, self is not representing anything, self is the instance.
OTHER TIPS
self
is being used in the shim you have listed to accommodate the fact that this
changes along with scope changes. Within the direct scope of the Function.prototype.bind function this
will refer to the object on which the bind function was called.
Once you enter the scope of the nested bound
function this
has changed; so the author has assigned self = this
within the bind
function to allow the value of this
at the time bind
is called to remain available to the bound
function via lexical scoping (closure).
Scoping within JavaScript can get pretty complicated; for a detailed explanation take a look at this article.