[英]Passing scope to forEach
我正在嘗試在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);
嘗試這樣的事情。 我已經使用了that
而不是_this
但我也移動了addToCount
所以它在countWords
里面。 這將countWords
變成一個包含它的閉包。
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;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.