IT源码网

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

developer 2021年03月09日 编程语言 453 0

回调函数中的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); 
    } 
};

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!