Consider this code sample:
var helper = {
isCheetah: function(a) {
return a === "Cheetah";
},
isLepoard: function(a) {
return a === "Lepoard";
},
researchedSpecies: function(a) {
return this.isCheetah(a) || isLepoard(a);
},
getResearchedSpecies: function(allSpecies) {
return _.filter(allSpecies, this.researchedSpecies);
}
};
// prints "isCheetah: true"
console.log("isCheetah:" + helper.isCheetah("Cheetah"));
// complains "this.isCheetah is not a function
helper.getResearchedSpecies(["Zebra",
"Cheeta",
"Lepoard",
"Godzilla"]);
Here is a live code on jsbin: http://jsbin.com/liyohumewe/edit?js,console
This works okay without lodash, in normal functions. Throw lodash into the mixute and the nested level functions no longer work. I guess it is because the this keyword, when invoked by lodash, doesn't refer to parent anymore, but to lodash instead (is that correct?).
Anyway, how do I work around that? How do I call the parent functions in a nested function invoked by lodash?
As requested by OP, copied from comments:
Bind the function reference to this using Function#bind.
Here is an updated JSBin.
See this MDN documentation for why you need to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With