24

クラスのメソッドの 1 つで 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(); 

ここで取り組んでいるフィドルがあります: http://jsfiddle.net/NhdDS/1/

4

3 に答える 3

54

厳密モードでは、プロパティ参照を介さず、何をすべきかを指定せに関数を呼び出すと、thisundefined.

forEach( spec | MDN ) を使用すると、何thisをすべきかを指定できます。これは、渡す (オプションの) 2 番目の引数です。

aGlobalVar.thing.prototype.amethod = function() {
  data.forEach(function(d) {
    console.log(d);
    console.log(this.value);
  }, this);
  // ^^^^
}

あるいは、矢印関数が 2015 年に JavaScript に追加されましたthis

aGlobalVar.thing.prototype.amethod = function() {
  data.forEach(d => {
    console.log(d);
    console.log(this.value);
  });
}
于 2013-10-18T09:03:27.740 に答える