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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:36:21  来源:igfitidea点击:

Accessing this in a forEach loop results in undefined

javascript

提问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 thisshould be, it's undefined.

在严格模式下,如果你通过属性引用调用一个函数,并且没有指定this应该是什么,它是undefined.

forEach(spec| MDN) allows you to say what thisshould 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, thiswill have the value undefinedby 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 thisvalue 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 forEachalso 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 thisin 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}>