MDN Function.prototype.bind bound function called as constructor

后端 未结 2 1166
别那么骄傲
别那么骄傲 2021-01-03 17:08

I know that when a function returned by Function.prototype.bind is called as a constructor, the pre-bound this is ignored. This is the behaviour sp

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 17:57

    But why do they need to create this dummy function (fNOP), instantiate it and assign to the fBound's prototype and so on.

    In case your bound function is called with new then this will be an instance of FNOP, this because the prototype of the returned function is an instance of FNOP.

    this instanceof fNOP will be true if I invoke the returned value with new. But only because the returned value has an instance of FNOP as it's prototype.

    If you would not create a dummy function and do:

        fBound = function () {
          return fToBind.apply(this instanceof fBound && oThis
    

    Then how would you set fBound's prototype? You could try:

       fBound.prototype = new fToBind();
    

    But the passed function may throw an exception when called without parameters, you could do:

       fBound.prototype = Object.create(fToBind.prototype);
    

    But then you need the polyfil for Object.create as well and that polyfill basically does the same thing; create a dummy function, set it's prototype and create an instance of the dummy function to have an object with it's prototype set.

提交回复
热议问题