在Javascript中,bind, apply, call方法都可以显式绑定上下文this,这三者有何不同呢?
bind只绑定this不马上执行
var person = { firstname: 'darren', lastname: 'ji', getFullName: function(){ var fullname = this.firstname + ' ' + this.lastname; return fullname; } }; //在浏览器中这里的this就是指向window var logName = function(arg1, arg2){ console.log(this.getFullName()); } //bind只是设置了this的指向,本身并不能执行 var logPersonName = logName.bind(person); //darren ji logPersonName();
call不仅绑定this,还马上执行,并接受可变参数
var person = { firstname: 'darren', lastname: 'ji', getFullName: function(){ var fullname = this.firstname + ' ' + this.lastname; return fullname; } }; //在浏览器中这里的this就是指向window var logName = function(arg1, arg2){ console.log(this.getFullName()); console.log('Arguments: ' + arg1 + ' ' + arg2); } //darren ji //Arguments: en es logName.call(person, 'en','es');
apply不仅绑定this,也马上执行,并接受数组
var person = { firstname: 'darren', lastname: 'ji', getFullName: function(){ var fullname = this.firstname + ' ' + this.lastname; return fullname; } }; //在浏览器中这里的this就是指向window var logName = function(arg1, arg2){ console.log(this.getFullName()); console.log('Arguments: ' + arg1 + ' ' + arg2); } //darren ji //Arguments: en es logName.apply(person, ['en', 'es']);