当前位置:主页 > 网页前端 > JavaScript代码 >

javascript 闭包疑问

时间:2021-02-18 11:19:18 | 栏目:JavaScript代码 | 点击:

复制代码 代码如下:

var test=(function() { var arr2=[1,2,3,3]; return function(){ return arr2; }; })()
Array.prototype.f1= function () { return []; }
Array.prototype.f2= function () { this.length=0; return this; }   

然后用两种方式调用:
一:var arr= test();
console.log(arr.length);结果是4
arr.f1();
arr= test();
console.log(arr.length);结果是4
这个好理解;

二:var arr= test();
console.log(arr.length);结果是4
arr.f2();
arr= test();
console.log(arr.length);结果是0
不知道为什么会这样,难道arr.f2()可以修改test函数中闭包中的arr2;

您可能感兴趣的文章:

相关文章