javascript - Anonymous function as callback -


this question has answer here:

i seeking understanding why way using anonymous functions erroring in circumstances.

in snippet below popuplate 2 arrays functions invoked @ later stage.

var arr1 = [];  var arr2 = [];    // callback function  var func = function(i){      return function(){$("body").append(i);}  };    var = 1;  while(i <= 5)  {      arr1.push(function(){$("body").append(i);});      arr2.push(func(i));    i++;  }    // invoke functions  $("body").append("output arr1 == ");  for(var c = 0; c < arr1.length; c++){ arr1[c](); }  $("body").append("<br> output arr2 == ");  for(var c = 0; c < arr1.length; c++){ arr2[c](); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

now, think understand why arr1 outputs 66666, because @ time of invocation, i == 6 , becuase has not been stored param within function @ time of creation, i retains it's last known value?

what really don't understand why recieve typeerror: arr2[c] not function when change callback function to:

var func = function(i){     $("body").append(i); }; 

why happen , appropriate / elegant way achieve functionality.

for first part of question, right, retain latest known value. avoid that, need use closure. example:

(function(x) {    arr2.push(func(x)); })(i); 

closure can used "scope hack". in case, ensure injected value constant current value of i.

for second part of question, confusion caused fact insert result of function (i.e.: func(i)) instead of function (func).

in first scenario, return explicit function(){...} array contain function can call operator "()".

in second scenario, in return $(<...>).append(), it's not guaranteed anymore return value function. in case, result "jquery" (see: jquery append) , not function, hence error correct. cannot use value function.

one way out is:

arr2.push(func); 

then:

arr2[c](c); 

or this:

(function(x){     arr2[x](x); })(c); 

if needed, can helpful console.log populated inside arrays before assuming right. since javascript not typed language, may go little while before suspecting wrong seem work intended.

hope helps!


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -