javascript 在 forEach 循环中访问它会导致未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19445599/
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
Accessing this in a forEach loop results in undefined
提问by Mike Rifgin
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 thisis undefined.
我在我的类的方法之一中使用 forEach 遍历数组。我需要访问在foreach内部的类的实例,但是这是不明确的。
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();
I have a fiddle I'm working on here: http://jsfiddle.net/NhdDS/1/.
我有一个我在这里工作的小提琴:http: //jsfiddle.net/NhdDS/1/。
回答by T.J. Crowder
In strict mode if you call a function notthrough a property reference and without specifying what this
should be, it's undefined.
在严格模式下,如果你不通过属性引用调用一个函数,并且没有指定this
应该是什么,它是undefined.
forEach
(spec| MDN) allows you to say what this
should be, it's the (optional) second argument you pass it:
forEach
( spec| MDN) 允许你说this
应该是什么,这是你传递的(可选)第二个参数:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(function(d) {
console.log(d);
console.log(this.value);
}, this);
// ^^^^
}
Alternately, arrow functionswere added to JavaScript in 2015. Since arrows close over this
, we could use one for this:
或者,箭头函数在 2015 年被添加到 JavaScript 中。由于箭头关闭this
,我们可以使用一个:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(d => {
console.log(d);
console.log(this.value);
});
}
回答by Qantas 94 Heavy
Since you're using strict mode, when a function is called that isn't a property of an object, this
will have the value undefined
by default (not the global object). You should store its value manually:
由于您使用的是严格模式,因此当调用不是对象属性的函数时,默认情况下this
将具有该值undefined
(不是全局对象)。您应该手动存储其值:
var aGlobalVar = {};
(function () {
"use strict";
aGlobalVar.thing = function () {
this.value = "thing";
};
aGlobalVar.thing.prototype.amethod = function () {
var self = this;
data.forEach(function (element) {
console.log(element);
console.log(self.value);
});
};
})();
var rr = new aGlobalVar.thing();
rr.amethod();
Nowadays, with ES2015 you can also use arrow functions, which uses the this
value of the outside function:
如今,在 ES2015 中,您还可以使用箭头函数,它使用this
外部函数的值:
function foo() {
let bar = (a, b) => {
return this;
};
return bar();
}
foo.call(Math); // Math
T.J. Crowder's solution of using the second argument of forEach
also works nicely if you don't like the idea of the temporary variable (ES5 code: works in pretty much any browser these days, except IE8-).
forEach
如果您不喜欢临时变量的想法,TJ Crowder 使用的第二个参数的解决方案也能很好地工作(ES5 代码:现在几乎可以在任何浏览器中使用,除了 IE8-)。
回答by Narcis
What I had to to is add this
in the every forEach that I was using (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). Binding in the constructor is not needed, as I am using arrow functions. So now my code is:
我必须this
在我使用的每个 forEach 中添加(参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)。不需要在构造函数中绑定,因为我使用的是箭头函数。所以现在我的代码是:
resetPressed = () => {
this.transport_options.forEach(function (transport_option) {
this.pressed_percentages.forEach(function (percentage) {
filters[transport_option][percentage] = false;
}, this)
}, this);
filters.isFilterActive = false;
this.setState({
filtersState: filters,
opacity: filters.isFilterActive ? 1 : 0.5
});
}
<TouchableHighlight
underlayColor={'transparent'}
onPress={this.resetPressed}
style={styles.iconView}>