The MDN bind polyfill is shown below.
I am trying to work out the purpose of
this instanceof fNOP ? this : oThis
in the fToBind.apply
invocation.
I can't get my head around it. Can someone help shed some light?
Function.prototype.bindMdn = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1)
, fToBind = this
, fNOP = function() {}
, fBound = function() {
return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
}
;
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
It seems to be a short-circuit if an instance of the bound function is supplied as the target when invoking the bound function, but the typeof check should catch this, so I don't understand its presence.
Link to the MDN page:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
Edit: This is a different question from the suggested duplicate. The suggested duplicate asks why fNOP
is needed. I fully grok that.
This question is why the instanceof
check is needed and what function it serves. I present my short-circuit hypothesis above, together with a reason why that doesn't fully make sense.