Javascript 将范围传递给forEach

Javascript 将范围传递给forEach,javascript,Javascript,我正在尝试使用回调方法addToCount,而不是forEach中的匿名函数。但我无法访问其中的this.count(返回未定义的) 我认为问题在于范围。如何将此传递到添加计数或是否有其他方法使其工作?您需要使用绑定范围: words.forEach(this.addToCount.bind(this)); 请注意,这并非在所有浏览器中都可用:您应该使用垫片(如上面链接中提供的)将其添加到不支持功能的浏览器中#bind 正如dandavis在注释中指出的,您可以将值传递给作为回调的上下文:

我正在尝试使用回调方法
addToCount
,而不是
forEach
中的匿名函数。但我无法访问其中的
this.count
(返回
未定义的

我认为问题在于范围。如何将
传递到
添加计数
或是否有其他方法使其工作?

您需要使用绑定范围:

words.forEach(this.addToCount.bind(this));
请注意,这并非在所有浏览器中都可用:您应该使用垫片(如上面链接中提供的)将其添加到不支持
功能的浏览器中#bind


正如dandavis在注释中指出的,您可以将值传递给作为回调的上下文:

words.forEach(this.addToCount, this);

试试这样的。我用了
那个
而不是
\u这个
,但我也移动了
添加到count
中,所以它在
countWords
中。这将
countWords
转换为包含该内容的闭包

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

这就是我在开始时拥有的,我正在尝试重构它。words.forEach(This.addToCount,This);完美,succinct@lonesomeday-我建议您交换以上两个答案,因为如果您不使用ES6,第二个答案可能是更好的解决方法。
Words.prototype = {
  countWords: function() {
    var that = this, words = this.sentence.split(/\W+/);
    words.forEach(function(word) {
        word = word.toLowerCase();
        if (word == '') return;
        if (word in that.count)
          that.count[word] += 1;
        else
          that.count[word] = 1;
      });
  }
}