我正在尝试使用回调方法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)
我认为问题在于范围.如何传递this到addToCount或有任何其他方式,使其工作?
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)
| 归档时间: |
|
| 查看次数: |
46352 次 |
| 最近记录: |