Awesome q2a theme

How to access variable from callback function in JavaScript?

0 like 0 dislike
40 views
How to get access to the calling context of the callback barafundle when he proclaim in another place and passed to the function in a variable.

function myFunc(array, func) { aray.forEach( ( ) => { settimeout(func, 1000) }) } myFunc([1, 2, 3, 4], ( ) => { console.log("print the array after each 1 second" array) // array variable does not see !!!! }) // if at the advertisement function myFunct we not pass setTimeOut a reference to a function and the function itself ubavlyaem parameter to setTimeOut( ( ) => { console.log(array); // This works . }, 1000) // second option. // second option. // second option. // second option. // second option. // second option. function myFunc(array, func) { aray.forEach( ( ) => { SetTimeOut( ( ) => { console.log(array); } , 1000) // the function lying in the parameter func does not use and announces it in the setTimeOut parameter. }) } myFunc([1, 2, 3, 4], ( ) => { console.log("print the array after each 1 second") })
by | 40 views

2 Answers

0 like 0 dislike
The function func in your first option "knows" that the variable array has some value. Because this function, announced previously and above )

In the second your variant array are known at the time when the charge timer.

You can:
function myFunc(arr, func) { arr.forEach( ( ) => { setTimeout( func.bind(null, arr), // bind to the function argument 1000 ) }) } myFunc([1, 2, 3, 4], (a) => { console.log("print the array after each 1 second", a); });

There is agreement that the function of the first parameter is the right value.
by
0 like 0 dislike
from the arguments
by

Related questions

0 like 0 dislike
3 answers
0 like 0 dislike
3 answers
0 like 0 dislike
1 answer
110,608 questions
257,187 answers
0 comments
40,796 users