Javascript 如何在lodash中的嵌套函数中调用父函数?
考虑以下代码示例:Javascript 如何在lodash中的嵌套函数中调用父函数?,javascript,lodash,Javascript,Lodash,考虑以下代码示例: var helper = { isCheetah: function(a) { return a === "Cheetah"; }, isLepoard: function(a) { return a === "Lepoard"; }, researchedSpecies: function(a) { return this.isCheetah(a) || isLepoard(a); }, getResearc
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上的实时代码:
在正常功能下,无需lodash,该功能正常工作。将lodash抛出到mixute中,嵌套的level函数将不再工作。我猜这是因为当lodash调用this
关键字时,它不再指父项,而是指lodash(正确吗?)
不管怎样,我该如何解决这个问题?如何在lodash调用的嵌套函数中调用父函数 根据OP的要求,从评论中复制: 使用
function\Bind
将函数引用绑定到此
有关需要执行此操作的原因,请参阅。
\uFilter
接受第三个参数作为上下文绑定。尝试将第三个参数this
传递给\uFilter
调用。或者,使用function\bind
将函数引用绑定到this
。(看看你为什么要这么做)。@sdgluck好极了,这很有效。。。你能把你的两个评论都写进一个答案吗please@RahilWazir,太好了,谢谢,你也可以把它写进答案里!