ここに例があります、
(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();