JavaScript, call (), apply (), bind () usage

" Use strict " ;
 var name = ' Wang ' , Age = 10 ;
 var obj = { 
    name: ' Li ' , 
    Age: 20 is , 
    getInfo ( from , to) { 
        the console.log (arguments) 
        the console.log ( the this + .name ' age is ' + the this .age + ' from: ' + from + ' to: ' + to); 
    } 
};

var DB = {name: ' Omura ' , Age: 96 }; 

obj.getInfo.call (DB, ' Beijing ' , ' Nanjing ' ); 
obj.getInfo.apply (DB, [ ' Inner Mongolia ' , ' Xinjiang ' , ' Villa ' ]); 
obj.getInfo.bind (DB, ' Shanghai ' , ' Tianjin ' ) ();

Above the latter method more months bind (), the result is returned all the way!

It follows that, bind returns a new function, you must call it will be executed.

Subtle gap!

It is obvious from the above four results:

call, bind, the first argument apply these three functions are pointing to this object, the second parameter is the difference came:

The call is to go directly into the parameter, the second and third n-th argument all separated by commas , directly into the back obj.myFun.call (db, 'Chengdu', ..., 'string') .

All parameters apply must be placed on a array which pass in obj.myFun.apply (DB, [ 'Chengdu', ..., 'String'] ).

In addition to returning a function other than bind, its parameters and the same call.

Of course, the parameter string is not limited to three types, allowing various types, including functions, object like!

 

Guess you like

Origin www.cnblogs.com/wanglijun/p/10988303.html