你的位置:首页 > Java教程

[Java教程]bind,apply,call的区别


 

在Javascript中,bind, apply, call方法都可以显式绑定上下文this,这三者有何不同呢?


bind只绑定this不马上执行

 

var person = {  firstname: 'darren',  lastname: 'ji',  getFullName: function(){    var fullname = this.firstname + ' ' + this.lastname;    return fullname;  }};//在浏览器中这里的this就是指向windowvar logName = function(arg1, arg2){  console.log(this.getFullName());}//bind只是设置了this的指向,本身并不能执行var logPersonName = logName.bind(person);//darren jilogPersonName();

 


call不仅绑定this,还马上执行,并接受可变参数

 

var person = {  firstname: 'darren',  lastname: 'ji',  getFullName: function(){    var fullname = this.firstname + ' ' + this.lastname;    return fullname;  }};//在浏览器中这里的this就是指向windowvar logName = function(arg1, arg2){  console.log(this.getFullName());  console.log('Arguments: ' + arg1 + ' ' + arg2);}//darren ji//Arguments: en eslogName.call(person, 'en','es');

 

apply不仅绑定this,也马上执行,并接受数组

 

var person = {  firstname: 'darren',  lastname: 'ji',  getFullName: function(){    var fullname = this.firstname + ' ' + this.lastname;    return fullname;  }};//在浏览器中这里的this就是指向windowvar logName = function(arg1, arg2){  console.log(this.getFullName());  console.log('Arguments: ' + arg1 + ' ' + arg2);}//darren ji//Arguments: en eslogName.apply(person, ['en', 'es']);