关闭不在函数范围之外工作

时间:2013-04-08 18:24:21

标签: javascript closures

刚开始学习闭包并在FireBug中编写了这段代码:

var later;

function outerFunc() {
  var innerVar = "Inside Outer";
  function innerFunc() {
     console.log(innerVar);
  }

  later = innerFunc;
};

outerFunc();
later();

但是在调用later();时,它返回一个未定义的值。不应该打印"Inside Outer" ?

1 个答案:

答案 0 :(得分:1)

var later;

function outerFunc() {
  var innerVar = "Inside Outer";
  function innerFunc() {
     console.log(innerVar);
  }

  later = innerFunc;
};

outerFunc(); //Don't run innerFunc, just set later = innerFunc
later(); // Execute innerFunc

所以它只记录了一次..看起来很不错..