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