javascript关闭 - 我怎么引用一个未声明的变量

时间:2014-11-27 13:59:37

标签: javascript closures

尝试让我了解javascript关闭,因为它们对我来说很陌生 我有一个指示使用的教程:

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

但我很担心" obs"。参数'障碍'自动传递给obs?

更好的例子可能是:

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 + "!"
         );
  };
}

2 个答案:

答案 0 :(得分:2)

您所获得的示例中缺少某些行,或者它不是关闭的正确示例。

是一个更好的例子(简化代码)
function warningMaker(obstacle){
   return function() {
      alert("Look!" + obstacle);
   }
}

上面的内容是,当函数返回时,对函数体中obstacle的引用会创建一个闭包,因此它将在内存中,并且只要被调用就会被使用,它将是

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

请注意,在上面,调用了返回的函数。 (我的意思是,空括号)

答案 1 :(得分:0)

我认为你的意思是:

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;
}