I'm trying to use a callback method addToCount instead of anonymous function in forEach. But I can't access this.count in it (returns 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;
}
}
I think the problem is the scope. How can I pass this to addToCount or is there any other way to make it work?