如何在forEach循环内使用'this'进行调用 [英] How to function call using 'this' inside forEach loop
问题描述
在以下对象中,使用'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));
});
}
}
我假设上下文正在发生变化而且'这个'指的是迭代的'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));
});
}
或使用bind:
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}.bind(this));
}
并注意,没有那些这个
将是窗口对象而不是obj。 此
始终是使用new关键字或window对象创建的对象(如果它是正常功能)。在严格模式中,此
在这种情况下将是未定义的。
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));
});
}
箭头功能没有自己的这个
他们从外部范围获得它。
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 page
这篇关于如何在forEach循环内使用'this'进行调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!