在forEach循环中访问它会导致未定义 [英] Accessing this in a forEach loop results in undefined
问题描述
我在我的一个Class方法中使用forEach迭代一个数组。我需要访问forEach中类的实例,但是这个是未定义的。
I'm iterating through an array using forEach in one of my Class's methods. I need access to the instance of the class inside the forEach but this is undefined.
var aGlobalVar = {};
(function () {
"use strict";
aGlobalVar.thing = function() {
this.value = "thing";
}
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(function(d) {
console.log(d);
console.log(this.value);
});
}
})();
var rr = new aGlobalVar.thing();
rr.amethod();
我有一个小提琴,我正在这里工作: http://jsfiddle.net/NhdDS/1/ 。
I have a fiddle I'm working on here: http://jsfiddle.net/NhdDS/1/ .
推荐答案
在严格模式下,如果你通过属性引用调用函数而不是并且没有指定这个,那么它是
undefined。
In strict mode if you call a function not through a property reference and without specifying what this
should be, it's undefined.
forEach
( spec | MDN )允许你说出这个
应该是什么,这是(可选)你传递的第二个参数:
forEach
(spec | MDN) allows you to say what this
should be, it's the (optional) second argument you pass it:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(function(d) {
console.log(d);
console.log(this.value);
}, this);
// ^^^^
}
或者, arrow functions 由于箭头关闭这个
,我们可以使用一个:
Alternately, arrow functions were added to JavaScript in 2015. Since arrows close over this
, we could use one for this:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(d => {
console.log(d);
console.log(this.value);
});
}
这篇关于在forEach循环中访问它会导致未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!