functionf1(){ var a = 1; //a是f1的局部变量 functionf2(){//f2是函数f1的内部函数,是闭包 a = a+1;//内部函数使用了f1中的变量a console.log(a); } return f2; } var test = f1(); test();//2 test();//3
代码中,外部函数 f1 只执行了一次,变量 a 设为 1 ,并将内部函数 f2 赋值给了变量 test 。由于外部函数 f1 已经执行完毕,其内部变量 a 应该在内存中被清除,然而事实并不是这样:我们每次调用 test 的时候,发现变量 a 一直在内存中,并且在累加。这就是闭包的神奇之处了!
使用闭包定义私有变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionpeople(){ var name; functiongetName(){ return name; } functionsetName(value){ name = value; } } var person = new people(); person.setName("张三");
Related Issues not found
Please contact @wangzhikui to initialize the comment