这是一个例子,
(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();