簡體   English   中英

將范圍傳遞給forEach

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM