簡體   English   中英

如何在lodash中的嵌套函數內調用父函數?

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

考慮以下代碼示例:

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

這是jsbin上的實時代碼: http ://jsbin.com/liyohumewe/edit?js,console

在普通函數中,沒有lodash,這可以正常工作。 將lodash扔進mixute並且嵌套級別函數不再起作用。 我想這是因為this關鍵字,當被lodash調用時,不再引用父級了,而是轉向lodash(這是正確的嗎?)。

無論如何,我該如何解決這個問題? 如何在lodash調用的嵌套函數中調用父函數?

根據OP的要求,從評論中復制:

使用Function#bind將函數引用綁定this

這是一個更新的JSBin。

請參閱此MDN文檔 ,了解您需要執行此操作的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM