forEachで無名関数の代わりにコールバックメソッド
addToCountを使おうとしています。しかし、その中の
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
に渡すことができるでしょうか、それとも他に方法があるでしょうか?
スコープをバインドするには、Function#bind
を使用する必要があります。
words.forEach(this.addToCount.bind(this));
これはすべてのブラウザで利用できるわけではないことに注意してください。Function#bind
をサポートしていないブラウザでは、シム(上記のリンクで提供)を使ってこれを追加する必要があります。
dandavisがコメントで指摘しているように、コールバックのコンテキストとしてArray#forEach
に値を渡すことができます。
words.forEach(this.addToCount, this);
こんな感じにしてみてください。私は _this
ではなく that
を使い、さらに addToCount
を移動して countWords
の中に入れています。これにより、countWords
はthatを含むクロージャになります。
Words.prototype = {
countWords: function() {
var that = this, words = this.sentence.split(/\W+/);
words.forEach(function(word) {
word = word.toLowerCase();
if (word == '') return;
if (word in that.count)
that.count[word] += 1;
else
that.count[word] = 1;
});
}
}