We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
No description provided.
The text was updated successfully, but these errors were encountered:
闭包是指有权访问另一个函数作用域中的变量的函数,创建一个闭包最常见的方式就是在一个函数内部创建另一个函数。
function f1() { var a = 1; function closure() { console.log(++a); } return closure; }
上面例子中,f1 内部的匿名函数以及它能够访问到的外部函数的变量 a 合在一起,就形成了一个闭包。使用 return 将闭包返回的目的是让它可以被外部访问。下面看看它怎么使用:
f1
a
return
var f2 = f1(); // 执行外部函数,返回闭包 f2(); // 2 f2(); // 3 f2(); // 4
第一句执行函数 f1() 后,闭包被返回并赋值给了一个全局变量 f2,以后每次调用 f2(),变量 a 的值就会加 1。通常函数执行完毕后,其作用域链和活动对象都会被销毁,为什么这里 a 并没有被销毁并且每次执行 f2() 还会被递增?原因是闭包有权访问外部函数的变量。
f1()
f2
f2()
1
Sorry, something went wrong.
No branches or pull requests
No description provided.
The text was updated successfully, but these errors were encountered: