如果将一个对象的方法作为回调函数传入,你需要定义一个确定的this,否则它将作为一个函数来执行,即this的指向会出现问题.例如:
我们想遍历一个数组,并把数组的每一项放入一个新数组,而这个新数组和push方法是一个对象obj的属性及方法,我们感觉正常写法如下
var obj={
ar:[],
push: function (c) {
console.log(this);-->打印window
this.ar.push(c);
}
}
var arr=[1,2,3];
arr.forEach(obj.push)
console.log(obj.ar);
但是却报错:TypeError: Array.prototype.push called on null or undefined 意思是在该对象上没有push方法,果然打印这个方法中的this是指向window的而不是obj,这自然无法调用obj的push方法,于是我们想到要修改this的指向,让它指向obj就好了
方法一:为forEach方法的第二个参数设置this指向的对象,这个参数一般我们用不到,因此被忽略了,不清楚的可以再去看一下forEach的基本使用方法,这样就正常了,我们打印一下push方法中的this指向也是正确指向了obj
var obj={
ar:[],
push: function (c) {
console.log(this);-->obj
this.ar.push(c)
}
}
var arr=[1,2,3];
arr.forEach(obj.push,obj)
console.log(obj.ar);--> [1, 2, 3]
方法二:我们还可以用bind来为this重新设置指向,让其指向obj
arr.forEach(obj.push.bind(obj));
方法三:在回调函数里面调用obj的push方法
arr.forEach(function (val) {
obj.push(val)
});
方法四:使用箭头函数,其实就是方法三的es6写法!这样可以保证其this就是一开始的指向
arr.forEach((val)=>obj.push(val));