【发布时间】:2013-11-01 19:11:57
【问题描述】:
我正在尝试使用回调方法 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 或者有其他方法可以让它工作吗?
【问题讨论】:
-
words.forEach(this.addToCount, this);
-
完美简洁
标签: javascript