[英]How does the Javascript closure with function works?
嗨,我一直在探索闭包和javascript核心概念,但我不明白为什么console.log(factory [i])输出未定义,我将函数推入其中了吗? 如果我在循环外调用temp,则表示未定义,而如果我在循环内调用,则返回有点困惑,有人可以解释一下吗?
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i]);
}
factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
temp(i);
console.log(factory[i]);
}
您不是在传递函数,而是传递已执行函数temp()的结果,因为它不会返回未定义的任何内容。 change factory.push(temp()); to factory.push(temp);
外部的temp()返回undefined,因为该时间循环已执行且i的值为2
请检查以下这段记录i值的代码。
var fruits=["apple","orange"]; var factory=[]; for(var i=0;i<fruits.length;i++) { var temp=function() { console.log(fruits[i],"console",i); } factory.push(temp); } temp(); console.log(factory,"factory"); for(var i=0;i<factory.length;i++) { temp(i); //i resets to 0 here in same scope console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed }
这是您的输出。
//next two executed due to factory.push(temp()) in first if loop
& there is a console.log there inside the function
apple
orange
//here i++ in first loop will be 3, but array have only two element, so it is undefined
undefined
// due to console.log(factory)
// temp function is actually returning undefined,
[undefined, undefined]
// due to temp(i) in second if block
apple
// but factory array is stil empty so factory[i] will be undefined
undefined
from temp orange
undefined
闭合不过是保留数据的功能。 到现在为止,一个函数被视为可以接受输入并产生一些输出的代码的平和度,对于每个函数调用,此代码都保持不变,但是闭包使您有机会使用该函数保存一些数据,这些数据可以更改,以便对于每个函数调用它会做出不同的反应,请记住一切都会变得容易。
假设您有一个找到利率的函数,但是利率不同的三个团队使用此函数,因此通常我们每次都要传递带有原则金额的团队名称,每次我们都要传递给团队name,所以通过使用闭包,我们可以为每个团队提供一个函数的三个实例(团队名称作为保存数据),现在仅发送本金并获得根据团队计算的利息,我现在还要添加示例,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.