1.Description:
I want to get a function array result. First, the func function adds anonymous functions to the array result (each anonymous function saves its own num)
But I passed the anonymous function after return with parameters, which is equivalent to just replacing it. Why are the results different?
function func(){
var result =[] ;
for(var i=0;i<3;i++){
result.push(
function (num){
return function (){
return num
}
}(i)
)
}
return result
}
console.log(func()[1]()) //这样我就能得到各自函数里的num
Below I pass the anonymous function after return as a parameter, but it cannot be obtained.
function func(fn){
var result =[] ;
for(var i=0;i<3;i++){
result.push(
function (num){
return fn;
}(i)
)
}
return result
}
function fn(){
return num
}
console.log(func(fn)[1]()) //报错提示num未定义
Because fn in the second piece of code is defined in the global environment.
You can take a look at the code here and below, I hope it will be helpful to you
This is a very simple scope problem. The formal parameters of the function defined in your loop only work in this function.
Functions should not be defined under loops or judgment conditions, as many unexpected problems will occur. Take out your function and define it, and you will find that the logic is much clearer.
Num scope problem, JavaScript has function scope, num is inside the first function, and the second function is outside the first function, then the second function cannot obtain num.