如何在 forEach 循环中使用“this"进行函数调用 [英] How to function call using 'this' inside forEach loop

查看:116
本文介绍了如何在 forEach 循环中使用“this"进行函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下对象中,我在使用this"引用时遇到问题:

In the following object, I have a problem using the 'this' reference:

function SampleObject(){
    this.addObject = function(object){...}
    ...
    // more code here
    ...
    this.addNewObjects= function(arr){
        arr.forEach( function (obj) {
            this.addObject(new Obj(obj.prop1, obj.prop2));
        });
    }
}

我假设上下文正在发生变化,并且this"指的是迭代的obj",而不是SampleObject".我已经使用普通的 for 循环解决了这个问题,但是我很好奇为什么这不起作用,并且想知道是否有另一种方法可以做到这一点.

I'm assuming the context is changing and that 'this' refers the iterated 'obj', and not 'SampleObject'. I've solved the problem using a normal for loop however, i'm curuois to why this is not working, and would like to know if there is another way to do this.

推荐答案

您可以将其存储在变量中:

You can store this in variable:

var self = this;
this.addNewObjects = function(arr){
    arr.forEach(function(obj) {
        self.addObject(new Obj(obj.prop1, obj.prop2));
    });
}

或使用绑定:

this.addNewObjects = function(arr) {
    arr.forEach(function(obj) {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    }.bind(this));
}

另外请注意,没有那些 this 将是窗口对象而不是 obj.This 始终是使用 new 关键字创建的对象或窗口对象(如果它是正常功能).在严格模式下 this 在这种情况下将是未定义的.

And side note, without those this will be window object not obj. This is always object that was created using new keyword or window object if it's normal function. In strict mode this will be undefined in this case.

UPDATE:在 ES6 中你可以使用箭头函数:

UPDATE: and with ES6 you can use arrow function:

this.addNewObjects = function(arr) {
    arr.forEach((obj) => {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    });
}

箭头函数没有自己的this,它们从外部作用域获取.

arrow functions don't have their own this and they get it from outer scope.

UPDATE2:来自@viery365 评论,您可以将其用作 forEach 的第二个参数,它将为函数创建上下文:

UPDATE2: from @viery365 comment you can use this as second argument to forEach and it will make context for the function:

this.addNewObjects = function(arr) {
    arr.forEach(function(obj) {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    }, this);
}

您可以在 MDN forEach 上阅读此内容

这篇关于如何在 forEach 循环中使用“this"进行函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆