我試圖在forEach
中使用回調方法addToCount
而不是匿名函數。但我無法訪問this.count
(返回undefined
)。將範圍傳遞給for each
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
或有任何其他方式使其工作?
words.forEach(this.addToCount,this); – dandavis
完美和簡潔 – rhysclay