JavaScript Closures 101: What is a closure?
wie Sie tun, machen, Film, Beispiel
4m 20sLänge
A JavaScript closure is a function that has a pointer reference to a free variable. A free variable is one that has fallen out of scope after its parent function has returned. However, if that outer function still has some reference to the free var (normally through a function that gets returned, or through a method property), the variable will not get garbage collected because it will have a non-zero reference count. Thus, from outside the function, we can still access the inner variable by means of the closure. Copyright (c) 2013 Rodrigo Silveira http://www.easylearntutorial.com
Kommentare
-
can anybody tell me when i need to use closures...? and give me real world example where closure exist..?
-
can anybody tell me when i need to use closures...? and give me real world example where closure exist..?
-
That's pretty cool explanation, to the point and very clear. Keep it up Rodrigo. and Thank you );
-
Awesome explanation! I finally understand this. What would be a case where we need to return the inner function?
-
I don't undersand why I got different in the final example .I type these in my chrome
function Person(name) {
var _name = name;
this.getName = function(){
return _name;
};
}
var me = new Person("Mihai");
but I got Person{};without name; -
cool.
-
awesome explanation.. Thank you!
-
:) :) :)
-
thank you so much
-
super clear genius
-
Great explanation! Thank you!
-
Waw in 4 min what others didn't explain in more than 20 min and long articles, so clear man thank you.
-
thanks a lot
-
在国内,看了许多“大神“讲解何为闭包基本上是一头雾水,其实我真的很怀疑他们到底自己有没有弄明白闭包概念。但是看到这个短短4分多钟的视频,豁然开朗,赞!!!
-
for those coming from c#, you can think of closures as how JS handles encapsulation. Think of properties. The JS inner function is the public property that is exposed. Then the public property has access to the JS parent function variables which are akin to the private fields in c#. Another way of saying this is that the JS parent function variables are private/hidden and only accessible through the JS inner function variables which are public/accessible from outside the function. - it's a convoluted thought process. If confused, yeah, just rewatch this video ... ;-)
-
Thank you. Good explained.
-
Thanks man. It's so simple when explained correctly. For hours I've been reading some lame examples in the net and you cleared everything in 2 minutes.
-
Next please do the object prototype inheritance.
This doesn't seem different from a standard 'getter' function to expose private fields in a class. If the excitement that the getter is attached to a function, not to a class? I've seen JavaScript patterns like Revealing Module Pattern to simulate OOP in JavaScript except using functions instead of classes.