Passing scope to forEach

后端 未结 2 1870
时光说笑
时光说笑 2020-12-05 02:06

I\'m trying to use a callback method addToCount instead of anonymous function in forEach. But I can\'t access this.count in it (return

相关标签:
2条回答
  • 2020-12-05 02:17

    Try something like this. I've used that rather than _this but also I've moved addToCount so it's inside countWords. That turns countWords into a closure containing 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;
          });
      }
    }
    
    0 讨论(0)
  • 2020-12-05 02:25

    You need to use Function#bind to bind a scope:

    words.forEach(this.addToCount.bind(this));
    

    Note that this is not available in all browsers: you should use a shim (as provided in the link above) to add it in the browsers that don't support Function#bind.


    As dandavis points out in the comments, you can pass a value to Array#forEach as the context for the callback:

    words.forEach(this.addToCount, this);
    
    0 讨论(0)
提交回复
热议问题