steo
steo

Reputation: 4656

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?

Upvotes: 3

Views: 427

Answers (3)

Vinod Kumar
Vinod Kumar

Reputation: 981

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.

Upvotes: 6

KJ Price
KJ Price

Reputation: 5994

Define someval outside the scope of the functions:

var someval; // <- outside of the scope of any one function
another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"

function a(fn){
  someval = "some-value"; // <-remove "var" to access the variable outside the scope
  return fn();
} 

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

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

Upvotes: 1

Amit K.
Amit K.

Reputation: 3754

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);
  }
}

Upvotes: 1

Related Questions