Handwriting bind function

Realization bind function

MDN reference Polyfill program offered

= Function.prototype.myBind function (context) {
   // here to make a judgment on the caller, if a function type is not directly Throws 
  IF ( typeof  the this ! == "function" ) {
     the throw 'must be a call function' 
  } 
  / / when we call the bind function, we may pass more than one parameter 
  // as fun.bind ({}, arg1, arg2) 
  // we need to come up behind parameters 
  let args = Array.prototype.slice.call ( arguments,. 1 ); 
  the let fToBind = the this ; 
  the let FNOP = function () {}; 
  the let fBound = function () {
     return fToBind.apply ( the this instanceof fNOP ? this : context, args.concat(arguments));
  }
  if(this.prototype){
    fNOP.prototype = this.prototype;
  }

  fBound.prototype = new fNOP();

  return fBound;
}

 

Here is a function fBound judge this instanceof FNOP In fact, this is to avoid a situation, because the bind function returns a function that, when we put this function is instantiated (that is, new fun ())

According to official documents when returning function is instantiated, this point will lock the point that instance, whether we passed parameter specifies this point.

At the following fBound inherit function we return a null function FNOP, when the function returns is instantiated, this FNOP the instanceof the result is true, this points to specify

function A () {}
 function B () {} 

a.prototype = new new B (); 

// If we return to the function instantiates   
the let C = new new A (); 
C the instanceof B // to true 
// but most we are 
A instanceof b // false

If you understand this, that the latter is simple, context parameters that we manually specify this point, when we bind bind will pass multiple parameters, time parameters will be executed, we need to bind

Function to get rid of the parameters and parameter when we call the way other than the first splicing

function foo () {}
 // example refers to args [arg1, arg2] 
// args.concat (arguments) is all arg1, arg2 ... arg4 parameters spliced 
the let newFoo = foo.bind ({ }, arg1, arg2); 
newFoo (arg3, ARG4);

In addition  arguments parameters do not confuse the above parameters that are obtained when the bind (that is, {}, arg1, arg2 )

The following arguments parameter refers to (is arg3, arg4) at the time of the call

Guess you like

Origin www.cnblogs.com/wangziye/p/11318934.html