On Mozilla Developer Center, there is a page about the Function.prototype.bind
function and provides a compatibility function for browsers which do not support this function.
However, when analyzing this compatibility code I cannot find out why they use instanceof nop
. nop
has been set to function() {}
. What part of the ECMA specification on bind
does this correspond with? And what variables are an instance of function() {}
?
The following returns false
, so I don't completely know what it is used for. What things return true when doing an instanceof function() {}
check?
(function() {}) instanceof (function() {}) // false
The code is as follows:
Function.prototype.bind = function( obj ) {
if(typeof this !== 'function')
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ),
args.concat( slice.call(arguments) ) );
};
bound.prototype = this.prototype;
return bound;
};
There seems to be an error with that implementation.
nop
is never used (to instantiate anything) expect for thatinstanceof
check, which can never be true for anything since no object can be instantiated fromnop
, which is buried deep in that closure.Consider this:
Someone edited out the part that makes it useful. Here's what it used to look like:
I answered another question that was asking the same thing (but when the code was correct) here: mozilla's bind function question.
The reason for the
this instanceof nop
check is so that if you call the bound function as a constructor (i.e. with thenew
operator),this
is bound to the new object instead of whatever you passed tobind
.To explain the "important part",
nop
is basically getting inserted into the prototype chain so that when you call the function as a constructor,this
is an instance ofnop
.So if you run
var bound = original.bind(someObject);
the prototype chain will look like this:My guess for why they used
nop
instead ofthis instanceof self
is so that the bound function would have it's ownprototype
property (that inherits fromself
's). It's possible that it's not supposed to which could be why it got partially edited out. Regardless, the code as it is now is not correct, but will work as long as you don't use the function as a constructor.