怎样在数组处理方法中使用this

回调函数中的this不做处理的话, this仍然会指向window, 解决方法有两种. 

第一种: 使用另一个变量固定this, 适用于在对象方法中使用的情况.

var obj = {
    arr: [1,2,3],
    powerArr: function(){
        var self = this;
        self.arr = self.arr.map(function (item) {
            console.log(self);
            return item**2;
        });
    }
};

obj.arr; // [1,2,3]
obj.powerArr(); // Object;
obj.arr; // [1, 4, 9]

下面是实际执行结果: 

第二种: 将this作为数组处理方法的第二个参数传递进去

var obj = {
    arr: [1,2,3],
    powerArr: function(){
        this.arr = this.arr.forEach(function(item){
            console.log(this);
            console.log(item**2);
        }, this);
    }
};

原文地址:https://www.cnblogs.com/aisowe/p/11660740.html