简体   繁体   中英

Trying to understand closures (JavaScript)

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

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>'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM