将范围传递给forEach

将范围传递给forEach

本文介绍了将范围传递给forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用回调方法addToCount代替forEach中的匿名函数.但是我无法访问其中的this.count(返回undefined).

I'm trying to use a callback method addToCount instead of anonymous function in forEach. But I can't access this.count in it (returns 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或还有其他方法可以使它工作?

I think the problem is the scope. How can I pass this to addToCount or is there any other way to make it work?

推荐答案

您需要使用绑定作用域:

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

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

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

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.

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

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);

这篇关于将范围传递给forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 08:13