Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: variable scope in callback

I'm trying to re-use variable inside a function that calls a callback, but it does not work the way I think it should;

another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"

function a(fn){
  var someval = "some-value";
  return fn();
} 

function callingfn(){
 return a.call(this, function(){
   console.log(someval)
  })
}

function another(){
  var sv = "somevalue";
  return function(){
    console.log(sv);
  }
}

I'm not able to understand if this is closure-related problem, but at first I expected that someval in callingfn would have been defined.

Where am I wrong?

like image 716
steo Avatar asked Aug 25 '26 09:08

steo


2 Answers

function fn() is different from a() though it receives fn as parameter.

You could possibly send someval as parameter.

another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"

function a(fn){
  var someval = "some-value";
  return fn(someval);
} 

function callingfn(){
 return a.call(this, function(someval){
   console.log(someval)
  })
}

function another(){
  var sv = "somevalue";
  return function(){
    console.log(sv);
  }
}

Or simply declare the var someval as global scope, currently it is inside a function which makes it local.

Hope this helps.

like image 133
Vinod Kumar Avatar answered Aug 26 '26 21:08

Vinod Kumar


Try This:

another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"
var someval;
var sv;

function a(fn){
  someval = "some-value";
  return fn();
} 

function callingfn(){
 return a.call(this, function(){
   console.log(someval)
  })
}

function another(){
 sv = "somevalue";
  return function(){
    console.log(sv);
  }
}
like image 34
Maverick Avatar answered Aug 26 '26 21:08

Maverick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!