Skip to content Skip to sidebar Skip to footer

Reason Behind Using 'instanceof Function() {}'?

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. Howev

Solution 1:

Someone edited out the part that makes it useful. Here's what it used to look like:

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 || {} ), 
                            args.concat( slice.call(arguments) ) );    
    };

    // These lines are the important part
    nop.prototype = self.prototype;
    bound.prototype = new nop();

    return bound;
};

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 the new operator), this is bound to the new object instead of whatever you passed to bind.

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 of nop.

So if you run var bound = original.bind(someObject); the prototype chain will look like this:

  original
     |
    nop
     |
   bound

My guess for why they used nop instead of this instanceof self is so that the bound function would have it's own prototype property (that inherits from self'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.


Solution 2:

There seems to be an error with that implementation. nop is never used (to instantiate anything) expect for that instanceof check, which can never be true for anything since no object can be instantiated from nop, which is buried deep in that closure.

Consider this:

// Identical definition, but different Function instances
var nop = function () {},
    mop = function () {};

var obj1 = new mop;

obj1 instanceof mop // true
obj1 instanceof nop // false

Post a Comment for "Reason Behind Using 'instanceof Function() {}'?"