52

addToCountで無名関数の代わりにコールバック メソッドを使用しようとしていますforEach。しかし、そこにはアクセスできませんthis.count( を返しますundefined)。

function Words(sentence) {
  this.sentence = sentence;
  this.count = {};
  this.countWords();
}

Words.prototype = {
  countWords: function() {
    var words = this.sentence.split(/\W+/);
    words.forEach(this.addToCount);
  },
  addToCount: function(word) {
    word = word.toLowerCase();
    if (word == '') return;
    if (word in this.count)
      this.count[word] += 1;
    else
      this.count[word] = 1;
  }
}

問題は範囲だと思います。どのように渡すことができthisますaddToCountか、それを機能させる他の方法はありますか?

4

2 に答える 2

81

Function#bindスコープをバインドするには、次を使用する必要があります。

words.forEach(this.addToCount.bind(this));

これはすべてのブラウザーで利用できるわけではないことに注意してください。サポートしていないブラウザーに追加するには、(上記のリンクで提供されているように) shim を使用する必要がありますFunction#bind


dandavis がコメントで指摘しているArray#forEachように、コールバックのコンテキストとして値を渡すことができます。

words.forEach(this.addToCount, this);
于 2013-11-01T19:14:58.043 に答える