Javascript 如何在 forEach 循环中使用“this”进行函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29626729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to function call using 'this' inside forEach loop
提问by user3339411
In the following object, I have a problem using the 'this' reference:
在以下对象中,我在使用“this”引用时遇到问题:
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));
});
}
}
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.
我假设上下文正在发生变化,并且“this”指的是迭代的“obj”,而不是“SampleObject”。我已经使用正常的 for 循环解决了这个问题,但是我很好奇为什么这不起作用,并且想知道是否有另一种方法可以做到这一点。
回答by jcubic
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));
});
}
or use bind:
或使用绑定:
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}.bind(this));
}
And side note, without those thiswill be window object not obj. Thisis always object that was created using new keyword or window object if it's normal function. In strict mode thiswill be undefined in this case.
并注意,没有那些this将是窗口对象而不是 obj。This如果它是正常功能,则始终是使用 new 关键字或 window 对象创建的对象。在this这种情况下,严格模式下将是未定义的。
UPDATE: and with ES6 you can use arrow function:
更新:使用 ES6,您可以使用箭头功能:
this.addNewObjects = function(arr) {
arr.forEach((obj) => {
this.addObject(new Obj(obj.prop1, obj.prop2));
});
}
arrow functions don't have their own thisand they get it from outer scope.
箭头函数没有自己的this,它们从外部作用域获取。
UPDATE2: from @viery365 comment you can use this as second argument to forEach and it will make context for the function:
UPDATE2:来自@viery365 评论,您可以将其用作 forEach 的第二个参数,它将为函数创建上下文:
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}, this);
}
You can read this on MDN forEach page
您可以在MDN forEach 上阅读此内容

