/* * 增加一层环境 */ function main(i){ return i}var demo = {}for(var i=0;i<5;++i){ ~function(){ var val = main(i); demo[i] = function(){ return val } }() }console.log(demo[4]())
/* * while 循环也一样 */ function main(i){ return i}var demo = {};var i = 5;while(i--){ ~function(){ var val = main(i); demo[i] = function(){ return val } }() }console.log(demo[1]())
/* * 经典的闭包 */ var i = 0, lis = document.getElementsByTagName('li'), val;while(val = lis[i++]){ ~function(){ var temp = i; val.onclick = function(){ console.log(temp) } }();}