Monday, December 31, 2018

javascript closure - how come I refer to an undeclared variable





Try to get my head around javascript closures as they are new to me.
I have a tutorial that indicates to use:



function warningMaker( obstacle ){
function doAlert (obs) {
alert("Beware! There have been "+obs+" sightings in the Cove today!");
};

return doAlert;
}


But I am confused about "obs". Does the parameter 'obstacle' automatically get passed to obs ?



A better example perhaps might be:



function warningMaker( obstacle ){
return function (number,location) {

alert("Beware! There have been " +
obstacle +
" sightings in the Cove today!\n" +
number + " " + obstacle +
"(s) spotted at the " +
location + "!"
);
};
}


Answer



Either the example you've got is missing some lines or it isn't a proper example for closure. A better example (with simplified code) would be



function warningMaker(obstacle){
return function() {
alert("Look!" + obstacle);
}
}



What the above does is, when the function is getting returned, the reference to the obstacle in the function body creates a closure so it will be in memory and will be used whenever called and it will be



warningMaker("Messi")(); // "Look! Messi"
warningMaker("CR7")(); // "Look! CR7"


Note that in the above, the function returned is being called. (I mean, the empty parentheses)


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...