我正在尝试使用回调方法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有任何其他方法可以使它工作?