2021年11月21日
js写一个闭包
一、什么是闭包
各种博客文献对闭包的定义非常抽象,五花八门。为了便于理解,个人认为:闭包就是能够读取其他函数内部变量的函数。由于在Javascript语言中,只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成”定义在一个函数内部的函数”。
所以,在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁。
二、写一个闭包
function fun1() {
var n = 99;
function fun2() {
n += 1;
console.log(n);
}
return fun2;
}
在上面的代码中,函数fun2被包含在函数f1内部,这时fun1内部的所有局部变量,对fun2都是可见的。但是反过来就不行,fun2内部的局部变量,对fun1就是不可见的。这就是Javascript语言特有的”链式作用域”结构(chain scope),子对象会一级一级地向上寻找所有父对象的变量。所以,父对象的所有变量,对子对象都是可见的,反之则不成立。
三、使用闭包的内存问题
1.方式一
fun1()() // 100
fun1()() // 100
为什么上面结果不符合预期,n没有自增。原因是fun1函数已经执行完毕了,没有其他资源引用 fun1 , fun1 会被立即释放,也就是说,fun1()()执行完后,立即就释放了。
2.方式二
var result = fun1()
result() //100
result() //101
result() //102
这次的结果符合预期,原因是fun1被result引用,result始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。这样持续调用下去就会导致内存泄漏。
解决内存泄漏问题
var result = fun1()
result() //100
result() //101
result() //102
result = null // 手动释放f1的引用 result
result = fun1()
result() //100
result() //101
Just wish to say your article is as amazing. The clarity in your post is just cool and
i could assume you are an expert on this subject. Well with your permission let me to grab your feed to keep up to date
with forthcoming post. Thanks a million and please carry on the enjoyable work.
Remarkable! Its genuinely remarkable paragraph, I have got much clear idea regarding from this piece
of writing.
Quality content is the important to attract the users to pay a quick visit the web page,
that’s what this site is providing.
I don’t even know how I ended up right here, however I thought this publish was good.
I don’t realize who you might be however definitely you are going to a well-known blogger if you are not already.
Cheers!
我們的台彩專家團隊採用智能AI預測系統,每日更新各大聯盟的比賽分析,包括NBA、MLB、中華職棒等。
Paver Installation Las Vegas and Paver Patio Installation Las Vegas
Disclosure de compliance virou conteúdo mainstream. Coisa louca de escrever, mas é isso.
Wizdom Wonders de novo. De boa.
O cara de ti com a planilha colocou R$30 no Dim Sum Prize e saiu com R$2.400. Sem print, só contou.
Os clipes de max win do Santa’s Gift Rush enganam — sessão média é bem mais calma.
Tigrinho me carregou hoje, kkkk.
Voltei pro Wild Wild Riches. Por quê.
Caishen Wins só caiu o bônus no giro 412 — antes disso, nada.
O reddit mudou de clipe de hype pra dado de sessão real esse ano.
O pessoal das lives resumão do fim de semana é a única coisa que leio na segunda.
Saí no green. Raro.
Rollover de 15x. Peguei o bônus.
Cansei do Wild Bandito essa semana.
Fortune Mouse só caiu o bônus no giro 412 — antes disso, nada.
Compra de bônus é imposto. Quase sempre.
I think I might disagree with some of your analysis. Are the figures solid?
I appreciate, cause I found just what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a great day. Bye -.
Your posts provide a clear, concise description of the issues.
I’m impressed, I need to say. Really rarely do I encounter a blog that’s both educational and entertaining, and let me tell you, you have hit the nail on the head.
You are not right. I am assured. I can prove it. Write to me in PM, we will talk.
I like your blog. It sounds every informative.
Fantastic piece of writing here1
I really like your writing style, excellent info , thanks for putting up : D.
I favored your idea there, I tell you blogs are so helpful sometimes like looking into people’s private life’s and work.At times this world has too much information to grasp. Every new comment wonderful in its own right.
We’re developing a conference, and it looks like you would be a great speaker.
You are a very smart person! 🙂
I saw a similar post on another website but the points were not as well articulated.
This contained some excellent tips and tools. Great blog publication.
The post is absolutely fantastic! Lots of great info and inspiration, both of which we all need! Also like to admire the time and effort you put into your website and detailed info you offer! I will bookmark your website!
Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here It’s always nice when you can not only be informed, but also entertained I’m sure you had fun writing this article.
I feel that is among the so much significant info for me. And i am satisfied studying your article. However should commentary on some basic issues, The site style is ideal, the articles is in reality excellent : D. Excellent activity, cheers
I thought it was going to be some boring old post, but I’m glad I visited. I will post a link to this site on my blog. I am sure my visitors will find that very useful.
Simply want to say your article is as amazing. The clarity in your post is just great and i can assume you’re an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.
Regards for helping out, superb info.
Just a quick note to express my appreciation. Take care
This is my first time i visit here. I found so many helpful stuff in your website especially its discussion. From the tons of responses on your posts, I guess I am not the only one having all the enjoyment here! keep up the excellent work
Our local network of agencies has found your research so helpful.
Great write-up, I am a big believer in placing comments on sites to inform the blog writers know that they’ve added something advantageous to the world wide web!
I know this is not exactly on topic, but i have a blog using the blogengine platform as well and i’m having issues with my comments displaying. is there a setting i am forgetting? maybe you could help me out? thank you.