2013-11-01 15 views
29

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

+6

words.forEach (this.addToCount, this); – dandavis

+0

Perfect & succinct – rhysclay

cevap

53

Bir kapsamını bağlamak için Function#bind kullanmak gerekir Bu Function#bind desteklemiyor.

dandavis yorumların işaret ettiği gibi

, sen geri arama için bağlam olarak Array#forEach bir değer geçirebilirsiniz:

words.forEach(this.addToCount, this); 
+0

@dystroy Gerçekten de, "Array # forEach", IE8'de bulunmuyor ... – lonesomeday

+20

forEach, 2. argüman olarak belirtmenize izin veriyor, bind ... – dandavis

+0

@dandavis Gerçekten, teşekkür ederim. Cevap güncellendi. – lonesomeday

1

Böyle bir şey deneyin. _this yerine that kullandım, ancak countWords'un içinde addToCount'u da taşıdım. Bu, countWords'u içeren bir kapatma içine döner.

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; 
     }); 
    } 
} 
+2

Bu, başlangıçta sahip olduğum şey ve bunu yeniden düzenlemeye çalışıyorum. – leemour