Extract function parameter from parent function

I have a function call in my script that contains a callback function call when calling fadeOut. I am trying to pass a parameter to a paren't function in a callback function, but I cannot get it to work.

General script structure:

function aFunction(aVar){ anElement.fadeOut(200, function(){ someFunctionCall(aVar); }); } 

The call is executed correctly, but the variable is not passed. This is probably the problem of defining a variable, but I do not quite understand this concept.

+4
source share
2 answers

This code

 function aFunction(aVar){ anElement.fadeOut(200, function(){ someFunctionCall(aVar); }); } 

is correct as indicated. Your internal function and any other functions that you declare automatically have access to all the variables in the content area. The function you pass to fadeOut will form a closure by aVar and continue accessing it even after the aFunction has long been back.

+6
source

You can save it in a local variable:

 function aFunction(aVar){ var new_var = aVar; anElement.fadeOut(200, function(){ someFunctionCall(new_var); }); } 
-1
source

Source: https://habr.com/ru/post/1385619/


All Articles