3

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?

3
  • someval is local to the function a() and will be accessible only inside a() and any closures inside a() (there are none in the code you posted). Commented Apr 9, 2015 at 13:55
  • Uhm, right. I was wondering if there was a way to make the callback a closure in a() Commented Apr 9, 2015 at 13:59
  • Thats not possible, for it to be a callback it has to be defined inside a() Commented Apr 9, 2015 at 15:41

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.