forEach
'da anonim işlev yerine bir geri arama yöntemi addToCount
kullanmaya çalışıyorum. Ancak this.count
'a erişemiyorum (undefined
döndürür).Kapsamı geçme alanı
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;
}
}
Sorun bence kapsam. this
'u addToCount
'a nasıl geçirebilirim veya çalışmasını sağlamak için başka bir yol var mı? Bu tüm tarayıcılarda kullanılabilir olmadığını
words.forEach(this.addToCount.bind(this));
Not: (yukarıdaki bağlantıda verilen gibi) tarayıcılarda eklemek için bir dolgu kullanmalıdır
words.forEach (this.addToCount, this); – dandavis
Perfect & succinct – rhysclay