Simple implementation of bind function in native js

  • 2021-07-09 07:10:44
  • OfStack

Today, I continued to study the implementation of bind function, and I also know the statements of shim and polyfill. Now, to summarize 1,


if (!Function.prototype.bind) {
 Function.prototype.bind = 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 && oThis
                 ? this
                 : oThis || window,
                aArgs.concat(Array.prototype.slice.call(arguments)));
    };

  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();

  return fBound;
 };
}

This is the implementation on the official document. I will talk about what I want to say in two aspects.

The first is the parameter, the use of agruments

var aArgs = Array. prototype. slice. call (arguments, 1). Here, the parameter array of bind function is taken out. The first parameter is not (that is, not oThis), that is, the object to be bound to the method, and the second is

aArgs. concat (Array. prototype. slice. call (arguments)); Here is the use of the array method, the parameters inserted in the parameters behind the array, note that this function is to be return out and then executed, his parameter array is return out of that fBound function parameter array, so the upper and lower two parameter array is not 1, a bit like Currization.

The second is context, in which context changes are difficult to understand, bind function is mainly used to bind context

fToBind = this This is the context in which the object is saved, followed by the following apply method so that the object to be bound can use this context

fNOP.prototype = this.prototype;

fBound.prototype = new fNOP();

Here, the attribute of the original object this. prototype is given to fBound with fNOP as the intermediary, so as to ensure that fBound is executed in the context at the time of definition. Originally

bound. prototype = self. prototype can integrate the original attributes, but so that both object attributes point to the same place, modifying bound. prototype will cause self. prototype to change, which is not our original intention. Therefore, through a null function nop, this situation can be effectively prevented.


Related articles: