String explanation in MDN polyfill binding

The following is an MDN polyfill binding.

I'm trying to determine the goal

this instanceof fNOP ? this : oThis 

in a call to fToBind.apply .

I can not get 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; }; 

This seems to be a short circuit if an instance of the related function is passed as the target when the related function is called, but the type check should catch it, so I don't understand its presence.

Link to MDN page:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Edit: This is another question from the proposed duplicate. The proposed duplicate asks why fNOP needed. I totally understand that.

This question is the need to check instanceof and what function it serves. I present the short circuit hypothesis above, as well as the reason why this does not make full sense.

+6
source share
1 answer

If you use the .bind result to create a new instance with new :

  function TestClass(a,b,c,d) { } var TestClassBound = TestClass.bindMdn(null, 1, 2, 3); new TestClassBound(); 

Then this instanceof fNOP is true .

typeof this !== 'function' simply checks to see if it was called in a regular way on the function, and not using call or apply , or to make sure it was not copied to the prototype of other objects. So this only prevents something like

 Function.prototype.bind.call("Not a function", 1, 2, 3); 

or

 var testObj = {}; testObj.bind = Function.prototype.bind; testObj.bind(1,2,3); 

For every regular bind call, the typeof this function will always be a function .

So, typeof this !== 'function' should check if the bind object is called, really a function.

And this instanceof fNOP inside fBind ensures that the behavior is correct when the binding result is used.

+4
source

All Articles