how come I refer to an undeclared variable
This question already has an answer here:
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)
我认为你的意思是:
function warningMaker( obstacle ){
var obs = obstacle; // otherwise it would never be able to associate this two variables automatically
function doAlert () {
alert("Beware! There have been "+obs+" sightings in the Cove today!");
};
return doAlert;
}
链接地址: http://www.djcxy.com/p/52024.html
上一篇: 它打印10次10次,我不明白为什么?
下一篇: 我如何参考未声明的变量