2015-09-17 107 views
2

考虑以下代码示例:如何在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调用this关键字时,不再引用父代,而是提示lodash(是否正确?)。

无论如何,我该如何解决这个问题?如何在由lodash调用的嵌套函数中调用父函数?

+2

'_.filter'接受第三个参数作为上下文绑定。尝试将第三个参数'this'传递给'_.filter'调用 –

+1

或者,使用'Function#bind'将函数引用绑定到'this'。 [请参阅此编辑。](http://jsbin.com/dogubiguzo/1/edit?js,console) – sdgluck

+1

(并参阅[此MDN文档](https://developer.mozilla.org/en-US/docs)/Web/JavaScript/Reference/Global_Objects/Function/bind)_why_你需要这样做)。 – sdgluck

回答