Arguments to JavaScript Anonymous Function

前端 未结 5 861
悲&欢浪女
悲&欢浪女 2021-02-13 11:47
for (var i = 0; i < somearray.length; i++)
{
    myclass.foo({\'arg1\':somearray[i][0]}, function()
    {
        console.log(somearray[i][0]);
    });
}
相关标签:
5条回答
  • 2021-02-13 11:56

    How about a closure:

    for (var i = 0; i < somearray.length; i++) {
        var val = somearray[i][0];
        myclass.foo({'arg1': val}, function(v) {
          return function() {console.log(v) };
        }(val) );
    }
    
    0 讨论(0)
  • 2021-02-13 12:01
    for (var i = 0; i < somearray.length; i++)
    
    {
        myclass.foo({'arg1':somearray[i][0]}, function(somearray)
        {
            console.log(somearray[i][0]);
        });
    }
    

    And then in method foo call anonymous function with param.

    0 讨论(0)
  • 2021-02-13 12:02

    The i in the anonymous function captures the variable i, not its value. By the end of the loop, i is equal to somearray.length, so when you invoke the function it tries to access an non-existing element array.

    You can fix this by making a function-constructing function that captures the variable's value:

    function makeFunc(j) { return function() { console.log(somearray[j][0]); } }
    
    for (var i = 0; i < somearray.length; i++)
    {
        myclass.foo({'arg1':somearray[i][0]}, makeFunc(i));
    }
    

    makeFunc's argument could have been named i, but I called it j to show that it's a different variable than the one used in the loop.

    0 讨论(0)
  • 2021-02-13 12:07

    All the functions/methods can be used as callbacks only. When you call the callback function you pass variables to it.

    var myclass = {
      foo: function(params, callback){
        // do some stuff
        callback(variable1, variable1, variableN);
      }
    }
    
    0 讨论(0)
  • 2021-02-13 12:18

    You can pass variables values to annoymous function by using callback, something like

    myclass.foo(function(variable){
          return function(){
            console.log(variable);
          }
        })(variableValue);
    );
    

    check this post: https://shahpritesh.wordpress.com/2013/09/06/javascript-function-in-loop-passing-dynamic-variable-value/

    0 讨论(0)
提交回复
热议问题