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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With