在浏览器控制台中执行以下代码,输出的结果是
function test() { var n = 4399; function add(){ n++; console.log(n); } return {n:n,add:add} } var result = test(); var result2 = test(); result.add(); result.add(); console.log(result.n); result2.add();
function test() { var n = 4399; function add(){ n++; console.log(n); } return {n:n,add:add} } var result = test(); var result2 = test(); result.add(); result.add(); console.log(result.n); result2.add();
4400 4401 4399 4400
4400 4401 4401 4402
4400 4400 4399 4400
4400 4401 4399 4402
4400 4401 4401 4400
{ n: 4399, add: function() { n++; console.log(n); //此 n 不是彼 n } }
test 构成了一个闭包, result 跟 result2 各自有自己的 test 作用域,所以最后 result2.add() 结果是 4400
var result=test(); // 执行 test 返回 {n:4399,add:add};
var result2=test(); // 同理,执行 test 返回 {n:4399,add:add};
result.add();
//test 构成闭包, add 作用域链包含 test 活动对象,所以 n++ ,会调用 test 活动对象的 n 累加,得到 4400
result.add(); // 和前面指向同一个 result 对象,所以不会初始化而是继续加 1 ,为 4001
console.log(result.n); //{n:4399,add:add}; 无关 add
result2.add(); // 作用域链有 test 活动对象,但是这个跟 result 的不是同一个。 4399+1= 4400
不同对象的闭包是彼此独立的,不相互影响。欢迎指正。