I came across the need to return a value from one function to another and for a while scratched my head in confusion when this simple task didn't work. I then realised I was operating within a closure function (or anonymous function?) and can't find documentation on how to release a variable out of such a function's scope.
For example, this doesn't work:
function aFunc()
{
var result;
object.event = function(){
result = true;
}
return result;
}
Nor does returning from inside the closure. Do I need to do both? I tried using a global variable within the largest scope possible (outside of all functions) and this didn't work either. What am I missing?
I'm not sure whether I'm using the term closure correctly, I'm referring to the anonymous function.
Thanks.
You need to call the closure:
function aFunc() {
var result;
object.event = function() {
result = true;
};
object.event();
return result;
}
Or, if it runs elsewhere, this is a timing issue. You can have something like a promise:
function aFunc() {
var promise = { hasRun: false, result: null };
object.event = function() {
result.hasRun = true;
result.result = true; // or something else...
};
return promise;
}
// check if it has run and get the result:
if (promise.hasRun) {
// access promise.result
}
But, a simple callback should suffice. Since you mentioned the XMLHttpRequest
object, you should be able to attach a callback to its onreadystatechange
event, or pass a callback to aFunc
:
function aFunc(callback) {
object.event = function() {
var result = true;
callback(result);
};
}
Then your callback gets called with the result at the time it is available.
You could pass an object to the closure, whose attribute 'result' it would set when the function is called.
function aFunc (foo) {
object.event = function() {
foo.result = true;
}
}
The problem is that the value of result
is returned by aFunc
, rather than a reference to it, which means that any subsequent change of result
that happens inside the closure would not affect the result
that was returned earlier.
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