You do not know the JS series (24) - ignored this

There are always exceptions to the rule, here, too. If you put null or undefined incoming call, apply or bind as the binding target of this application is the default binding rules
function foo(){
  console.log(this.a);
}
var a = 2;
foo.call(null); // 2

 

 

What would pass null it?
function foo (A, B) { 
  the console.log ( "A:" + + A ", B:" + B); 
} 
// the array "expand" into the parameter 
foo.apply ( null , [2,3 ]) ; 

// use the bind () for currying (pre-set parameters) 
var bar = foo.bind ( null , 2 ); 
bar ( . 3);

If the function does not care about this, you still need to pass a placeholder value, then a null eating it is a good choice, if one does use this function, the default rule is bound to the global object to this, it will lead to unpredictable consequences, such as modifying the global object.



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

// we DMZ objects 
var Ø = the Object.create ( null ); 

// the array " expand "a parameter 
foo.apply (Ø, [2,3 ]); 

// use the bind () for currying (pre-set parameters) 
var bar = foo.bind (Ø, 2 ); 
bar ( . 3);

Use variable names not only allows the function to become more "safe", but also improve the readability of the code, because ø said, "I hope this is empty", which is better than the meaning of null

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/12446591.html