javascript 将范围传递给 forEach

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19733758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:39:10  来源:igfitidea点击:

Passing scope to forEach

javascript

提问by leemour

I'm trying to use a callback method addToCountinstead of anonymous function in forEach. But I can't access this.countin it (returns undefined).

我正在尝试使用回调方法addToCount而不是forEach. 但我无法访问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;
  }
}

I think the problem is the scope. How can I pass thisto addToCountor is there any other way to make it work?

我认为问题在于范围。我如何传递thisaddToCount或有其他方法可以使其工作?

回答by lonesomeday

You need to use Function#bindto bind a scope:

您需要使用Function#bind来绑定范围:

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.

请注意,这并非在所有浏览器中都可用:您应该使用 shim(如上面的链接中提供的)将其添加到不支持Function#bind.



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

正如 dandavis 在评论中指出的,您可以传递一个值Array#forEach作为回调的上下文:

words.forEach(this.addToCount, this);

回答by NickM

Try something like this. I've used thatrather than _thisbut also I've moved addToCountso it's inside countWords. That turns countWordsinto a closure containing that.

尝试这样的事情。我使用了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;
      });
  }
}