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
Post a Comment