apply, call, bind the null

If null or undefined as this is bound object passed to the call, apply or bind, these values ​​are ignored when you call, the practical application of the default binding rules:

function foo(){
  console.log(this.a)  
}

var a = 2;

foo.call(null); // 2

Then it will pass null under what circumstances?

A very common practice to use apply (..) to 'expand' an array, and as an argument to a function.

Similar, the bind (..) may force of the parameters Ke (pre-set parameters) ( ES6 operator may use ... ) , this method is very useful

function foo (A, B) { 
  the console.log ( "A:" + + A ", B:" + B)   
} 

// the array 'expand' a parameter 
foo.apply ( null , [2,. 3]) / / A: 2, B:. 3 

// use the bind (..) for currying 
var bar = foo.bind ( null , 2 ); 
bar ( . 3); // A: 2, B:. 3

Both methods need to pass a parameter as a binding target of this. If the function does not care about this, you still need to pass in an accounting position, then null is a good choice.

 Taken you do not know javascript

 

Guess you like

Origin www.cnblogs.com/firstsight/p/12383316.html