将范围传递给forEach

lee*_*our 42 javascript

我正在尝试使用回调方法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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为问题在于范围.如何传递thisaddToCount或有任何其他方式,使其工作?

lon*_*day 69

您需要使用Function#bind绑定范围:

words.forEach(this.addToCount.bind(this));
Run Code Online (Sandbox Code Playgroud)

请注意,并非所有浏览器都提供此功能:您应该使用填充程序(如上面的链接中所提供的)将其添加到不支持的浏览器中Function#bind.


正如dandavis在评论中指出的那样,您可以将值传递给Array#forEach回调的上下文:

words.forEach(this.addToCount, this);
Run Code Online (Sandbox Code Playgroud)

  • forEach允许你指定它作为它的第二个参数,不需要使用bind ... (28认同)
  • @lonesomeday - 我建议交换上面的两个答案,因为如果你不使用ES6,第二个可能是今天更好的方法. (2认同)