Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  190] [ 6]  / answers: 1 / hits: 60295  / 11 Years ago, fri, november 1, 2013, 12:00:00

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


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


More From » javascript

 Answers
59

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

[#74554] Thursday, October 31, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;