简体   繁体   中英

How do I call a parent function inside a nested function in lodash?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM