将范围传递给 forEach

2024-05-07

我正在尝试使用回调方法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 to addToCount或者还有其他方法可以使其发挥作用吗?


你需要使用Function#bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind绑定范围:

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

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


正如 dandavis 在评论中指出的那样,您可以将值传递给Array#forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach作为回调的上下文:

words.forEach(this.addToCount, this);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将范围传递给 forEach 的相关文章

随机推荐