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
Passing scope to forEach
提问by leemour
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
).
我正在尝试使用回调方法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 this
to addToCount
or is there any other way to make it work?
我认为问题在于范围。我如何传递this
给addToCount
或有其他方法可以使其工作?
回答by lonesomeday
You need to use Function#bind
to 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#forEach
as the context for the callback:
正如 dandavis 在评论中指出的,您可以传递一个值Array#forEach
作为回调的上下文:
words.forEach(this.addToCount, this);
回答by NickM
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.
尝试这样的事情。我使用了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;
});
}
}