javascript闭包
理解了下面几个例子,对于闭包,应该可以算是入门了。
1.
function say667() {
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayAlert = say667();
sayAlert();
2.
function setUpSomeGlobals() {
var num = 666;
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
setUpSomeGlobals(); //为三个全局变量赋值
gAlertNumber(); //666
gIncreaseNumber();
gAlertNumber(); //667
gSetNumber(12);
gAlertNumber(); //12
3.
function buildList(list) {
var result = [];
for(var i = 0; i < list.length; i++) {
var iteml = 'item' + list[i];
result.push( function() { alert(item + ' ' + list[i]); });
}
return result;
}
function testList() {
var fnlist = buildList([1, 2, 3]);
for(var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
4.
function sayAlice() {
var sayAlert = function() { alert(alice); }
var alice = 'Hello Alice';
return sayAlert;
}
var helloAlice = sayAlice();
helloAlice(); //Hello Alice
5.
function newClosure(someNum, someRef) {
var num = someNum;
var anArray = [1,2,3];
var ref = someRef;
return function(x) {
num += x;
anArray.push(num);
alert('num: ' + num + '\nanArray ' + anArray.toString() + '\nref.someVar ' + ref.someVar);
}
}
closure1 = newClosure(40, { someVar: 'closure 1'});
closure2 = newClosure(1000,{ someVar: 'closure 2'});
closure1(5);
closure2(-10);