Why can anonymous functions defined with `var` be called in global scope?

function setupSomeGlobals() {
  // Local variable that ends up within closure
  var num = 666;
  // Store some references to functions as global variables
  var gAlertNumber = function() { console.log(num); }
}

setupSomeGlobals();

gAlertNumber(); //works, WHY?!!

console.log(num); //does not work, GOOD

我希望gAlertNumber()不能在setupSomeGlobals()函数之外工作......


Variables declared with var are always going to be local and won't be accessible from the outside.

If you run this in the console, it is more likely that you might have polluted the global namespace through earlier tries. Open a new tab and run the code again.

链接地址: http://www.djcxy.com/p/51694.html

上一篇: 匿名函数返回类属性? PHP

下一篇: 为什么在全局范围内调用`var`定义的匿名函数?