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;
  }
}

我认为问题在于范围。我怎样才能通过thisaddToCount有任何其他方法可以使它工作?

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 回答
2

尝试这样的事情。我用过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;
      });
  }
}
于 2013-11-01T19:24:46.360 回答