一、在调用时修改:call()与apply()
var obj1 = {
age : 10,
say : function(){console.log(this.age);}
}
var obj2 = {age : 20,}
obj1.say.call(obj2); // 20
//(call()能在调用的时候修改this指向)
obj1.say.apply(obj2); // 20
//(apply()也能在调用的时候修改this指向)
注意点:call()与apply()的区别:
当要才传递参数时,call()直接使用逗号分隔,apply()使用数组。
var obj1 = {
age : 10,
say : function(a,b,c){console.log(this.age);console.log(a+b+c);}
}
var obj2 = {age : 20,}
obj1.say.call(obj2,1,2,3); // 20 6
obj1.say.apply(obj2,[2,3,4]); // 20 9
二、在定义(封装)时修改:.bind()
var obj1 = {
age : 10,
say1 : function(){console.log(this.age);}
}
var obj3 = {
age : 30,
say3 : function(){console.log(this.age);}.bind(obj1);}
//bind()在函数封装的时候直接修改了this指向
}
obj3.say3(); // 10
在定时器中的应用:
定时器的this指向window,可以通过.bind()修改
var obj4 = {
age : 40,
say4 : function(){
setTimeout(function () {
console.log(this.age);
}.bind(this), 1000); // 40
//将定时器中的this改为定时器外一层的this,即obj4
}
}
三、通过备份来代替this:
点击的DOM事件中,点的是谁,在事件处理函数中this就指向谁。
因此在操作DOM时,可以声明变量备份this,var _this=this;来避免在处理函数中的this指向改变。定时器同样可以。
function Fn (name){this.name = name;}
Fn.prototype.init = function () {
var _this = this; // 声明变量,备份保存,该this指向Fn
setTimeout(function () {
console.log(this); // window
console.log(_this); // Fn
console.log(_this.name); // zhangsan
}, 1000);
}
var fn = new Fn("zhangsan");
四、利用箭头函数改变this指向:
箭头函数的特点就是没有自身的this。
利用这一特性可以直接指向外层。
function Fn (name){this.name = name;}
Fn.prototype.init = function () {
setTimeout(() => {
console.log(this); //Fn
console.log(this.name); // zhangsan
}, 1000);
}
var fn = new Fn("zhangsan");