callback - 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 above code, don't understand purpose serves have if-else statement returned in function. wouldn't same effect if had following instead?

function myfunc(inputfunc){   var called = false;   if (!called) {     called = true;     var storedresult = inputfunc();     return storedresult;   }   else     return storedresult;   } 

wouldn't same...

not really, outer function returns function, enclosing called variable in it's scope doesn't change in later calls
here's how first code snippet work

var instance = inputfunc();  var storedresult = instance(); // returns result  var runitagain = instance(); // returns `undefined` 

your second version wouldn't of that, be

var storedresult = inputfunc(); // result  var runitagain = inputfunc(); // result again, "called" variable false 

in other words, first version returns result once, , once, here's 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>';


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -