search

Home  >  Q&A  >  body text

javascript - Questions about function closures and passing functions as parameters

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

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-06-26 10:52:31

    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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-26 10:52:31

    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.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:52:31

    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.

    reply
    0
  • Cancelreply