Reputation: 8193
function myFunc(inputFunc){
var called = false;
return function() {
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
}
else
return storedResult;
};
}
In the above code, I don't understand what purpose it serves to have the if-else statement returned in a function. Wouldn't it be the same effect if I just had the following instead?
function myFunc(inputFunc){
var called = false;
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
}
else
return storedResult;
}
Upvotes: 1
Views: 28
Reputation: 318362
Wouldn't it be the same...
Not really, the outer function returns a function, enclosing the called variable in it's scope so it doesn't change in later calls
Here's how the first code snippet would work
var instance = inputFunc();
var storedResult = instance(); // returns the result
var runItAgain = instance(); // probably returns `undefined`
Your second version wouldn't do any of that, it would just be
var storedResult = inputFunc(); // result
var runItAgain = inputFunc(); // result again, the "called" variable is always false
In other words, the first version returns the result once, and only once, here's a snippet
function myFunc(inputFunc) {
var called = false;
return function() {
if (!called) {
called = true;
var storedResult = inputFunc();
return storedResult;
} else
return storedResult;
};
}
var instance = myFunc(function() {
return 'result';
});
var log = [];
log.push( instance() ); // result
log.push( instance() ); // undefined
log.push( instance() ); // undefined
log.push( instance() ); // undefined
document.body.innerHTML = '<pre>' + JSON.stringify(log, null, 4) + '</pre>';
Upvotes: 4