1,关于闭包的简单实现
//example 1
function sayHello(name) {
var words = "hello," + name;
var sayForAlert = function () {
alert(words);
}
sayForAlert();
}
//sayHello("jack");
/*
An Example of a Closure
Two one sentence summaries:
a closure is the local variables for a function — kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns (as if a ‘stack-frame‘ were malloc‘ed instead of being on the stack!).
*/
function sayHello2(name){
var words = "hello, "+name; //local variables;
var sayForAlert = function (){
alert(words);
}
function buildList( list ){
var result = [];
for (var i = 0 ; i<list.length; i ++){
var item = ‘item‘ + list[i];
result.push(function(){alert(item +‘ ‘+list[i])});
}
return result;
}
function testList(){
var fnList = buildList([1,2,3,4]);
for(var j=0; j < fnList.length; j ++){
fnList[j]();
}
}