Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

写出代码执行结果 #12

Open
MaMaFish opened this issue Mar 5, 2020 · 0 comments
Open

写出代码执行结果 #12

MaMaFish opened this issue Mar 5, 2020 · 0 comments

Comments

@MaMaFish
Copy link
Owner

MaMaFish commented Mar 5, 2020

function Foo() {
    var i = 0 ;
    return function() {
        console.log(i++)
    }
}

var f1 = Foo();
var f2 = Foo();

f1();
f1();
f2();

结果是:
0
1
0

闭包的用途:

  1. 访问外部函数的变量。
  2. 使被外部函数引用的变量一直保存在内存中。

这是一个闭包,闭包可以通过作用域链向上访问外层函数的变量和函数,同时闭包的作用域链上引用了外部函数的活动对象。
所以当f1();函数调用结束后,按道理来讲,这里的变量应该被回收,内存应该被释放,但由于外层函数的活动对象被子作用域链引用,一直保存在内存中,输出结果为0,之后i++ 变为1,当再次调用f1()时,存在于内存中的变量i=1,打印输出,不过变量i还一直存在,除非手动设置为i=null;

@MaMaFish MaMaFish changed the title 第12题:写出代码执行结果 写出代码执行结果 Nov 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant