this指向的解释你可能知道了,但是当在某些场景下还是会误导你的,比如回调函数中的this。
不信看看下面的例子:
var a = {
statusArr: [],
on: function (state) {
this.statusArr.push(state);
return a;
},
fire() {
/**
* 是否将this存起来
*/
//箭头函数
// this.statusArr.forEach((state)=>{
// console.log(this);//a 对象
// this.actionArr[state]();
// });
//普通函数
var self = this;
this.statusArr.forEach(function (state) {
console.log(this == global); //node环境 true
console.log(this == window); //浏览器环境 true
self.actionArr[state]();
});
//亦或是 通过bind改变回调函数中this的指向
this.statusArr.forEach(function (state) {
console.log(this);
this.actionArr[state]();
}.bind(this));
},
actionArr: {
jump: function () { },
run() { console.log('run !!!') },
actionArr: {
jump: function () { },
run: function () { },
fire: function () { }
}
}
}
a.on('run').fire();
解决问题的办法:回调函数作为参数传过去的。就是普通函数。
误解:认为箭头函数中的this是this.statusArr
//箭头函数
// this.statusArr.forEach((state)=>{
// console.log(this);//错误猜测:this为this.statusArr
// this.actionArr[state]();
// });