Wednesday, 26 April 2017

javascript closure - how come I refer to an undeclared variable

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...