javascript - Questions about function closures and passing functions as parameters
世界只因有你
世界只因有你 2017-06-26 10:50:31
0
3
827

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未定义
  
世界只因有你
世界只因有你

reply all(3)
Ty80

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

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;
}
var num = 1;
console.log(func(fn)[1]()); //1
给我你的怀抱

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template