JavaScript Why return function in a function? -


var favoritecolor = "blue"; function colorgenerator(color) {     return function () { return color; }; } var getcolor = colorgenerator(favoritecolor); 

why getcolor not blue. getcolor() blue. getcolor becomes function? because return function in colorgenerator?

i confused these. thank help.

let's dissect this:

var favoritecolor = "blue"; function colorgenerator(color) {     return function () { return color; }; } 

this method returns function that, in turn, returns value (color). doing this:

var getcolor = colorgenerator(favoritecolor); 

means getcolor function() {return "blue";}. therefore, doing:

getcolor(); 

after setting value return "blue".


test:

var favoritecolor = "blue";  function colorgenerator(color) {      return function () { return color; };  }  var getcolor = colorgenerator(favoritecolor);    document.getelementsbyclassname("foo")[0].innerhtml = "colorgenerator returns: " + colorgenerator(favoritecolor);  document.getelementsbyclassname("bar")[0].innerhtml = "getcolor returns: " + getcolor();
<div class="foo"></div>  <div class="bar"></div>


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -