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か、それを機能させる他の方法はありますか?