這裏答案是一個例子,
(function() {
console.log(1);
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { console.log(num); }
num++;
return sayAlert();
})();
這將定義之後立即調用。
與您的代碼
所以,
function setupSomeGlobals() {
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
gAlertNumber();
}
setupSomeGlobals();
在這裏,你可以調用子功能gAlertNumber()
父功能setupSomeGlobals()
內,你不能在父函數外部訪問它。
但是你可以調用父函數之後調用此,這意味着不調用gAlertNumber()
父函數內。把它調用父等之後,
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
setupSomeGlobals();
gAlertNumber();
你不能在函數之外訪問它,因爲它不在範圍之內,並且你沒有可訪問的引用 – musefan
@Jeffman,@musefan:'gAlertNumber'是一個全局變量。爲什麼你認爲它不能在'setupSomeGlobals'之外訪問? [小提琴](http://jsfiddle.net/j5yTn/) – Andreas
這是一個不錯的方法來初始化的全局變量,你真的不應該反正使用全局變量。在「嚴格」模式下,這將是一個錯誤。 – Pointy