简体   繁体   English

试图了解闭包(JavaScript)

[英]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. 在上面的代码中,我不明白在函数中返回if-else语句的目的是什么。 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>'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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