将范围传递给 forEach

Passing scope to forEach

本文关键字:forEach 范围      更新时间:2023-09-26

我正在尝试使用回调方法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,或者有没有其他方法可以使其工作?

您需要使用 Function#bind 来绑定作用域:

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

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


正如 dandavis 在注释中指出的那样,您可以将一个值传递给 Array#forEach 作为回调的上下文:

words.forEach(this.addToCount, this);

试试这样的事情。我用了that而不是_this,但我也addToCount移动了,所以它在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;
      });
  }
}