javascript closure - how come I refer to an undeclared variable
本问题已经有最佳答案,请猛点这里访问。
尝试让我的头脑围绕着javascript闭包,因为它们是我的新产品。我有一个教程指出要使用:
1 2 3 4 5 6 | function warningMaker( obstacle ){ function doAlert (obs) { alert("Beware! There have been"+obs+" sightings in the Cove today!"); }; return doAlert; } |
但我对"obs"感到困惑。"障碍物"参数是否自动传递给OBS?
一个更好的例子可能是:
1 2 3 4 5 6 7 8 9 10 11 12 | function warningMaker( obstacle ){ return function (number,location) { alert("Beware! There have been" + obstacle + " sightings in the Cove today! " + number +"" + obstacle + "(s) spotted at the" + location +"!" ); }; } |
要么您得到的示例缺少一些行,要么它不是一个合适的闭包示例。一个更好的例子(使用简化的代码)是
1 2 3 4 5 | function warningMaker(obstacle){ return function() { alert("Look!" + obstacle); } } |
上面所做的是,当函数返回时,函数体中对
1 2 | warningMaker("Messi")(); //"Look! Messi" warningMaker("CR7")(); //"Look! CR7" |
注意,在上面,正在调用返回的函数。(我是说,空括号)
我认为你的意思是:
1 2 3 4 5 6 7 | 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; } |