有这样的3个方法可以改变函数体的this指向:
var test = function(x){
console.log(this.a);
console.log(x);
};
//bind 方法,bind方法返回一个指定this对象的函数,对源函数没有影响。-----------
var bdingFn = test.bind({a: 'bindding'});
bdingFn(9);
//'bindding'
//9
//另外,可以给test函数换一个this对象 -----------
var bdingFn1 = test.bind({a: 'this changed'}); //这一执行不影响先前绑定返回的函数
bdingFn1(10);
//'this changed'
//10
//注意,bing方法返回的函数不能通过call或apply的调用而改变this的指向----!!!!
bdingFn.call({a: 'attend to change the this'}, 288);
//'bindding'
//288
//call方法,跟apply一样暂时改变this的指向,对源函数没有影响。--------------
test.call({a: 'call'}, 9);
test(9);
//'call'
//9
//apply跟call的作用一样,只是apply的第二参数在传值时是个数组----------------
test.apply({a: 'apply'}, [9]);
//'apply'
//9
//call方法和apply方法的参数皆可选,当thisArg参数为null或不传值时,不会改变this的指向--------
test.apply();
test.call();
//以及bind方法也是
test.bind()();
//如果函数体有返回值,那么apply和call的调用、bind返回的函数的调用也会返回同样的值--------
//关于bind,bind还可能绑定函数地参数,一旦bind,不能修改,后续传给bind返回地函数地参数,-----
//都将续在之前绑定的参数后面
var test = function(){
console.log(arguments);
}
var fn = test.bind(null, 2, 4);
fn();
//Arguments[2, 4 ,...]
fn(10, 9);
//Arguments[2, 4 , 10, 9, ...]
其他文档: