I was reading a book and came across "Closure in javascript limits the scope of variables in the function".. does that mean, if any another object which inherits from the function object with closure , cannot access its properties
-
Closures have no effect on scope, they are a consequence of scope.RobG– RobG2013-04-23 03:09:24 +00:00Commented Apr 23, 2013 at 3:09
-
what do you mean "inherit from the function"?Sebas– Sebas2013-04-23 03:13:37 +00:00Commented Apr 23, 2013 at 3:13
-
the closure properties cannot be accessed from inherited function. I hope you are talking about protorypical inheritanceArun P Johny– Arun P Johny2013-04-23 03:17:39 +00:00Commented Apr 23, 2013 at 3:17
-
Maybe provide some code which shows the kind of declarations you're asking about.Mike Samuel– Mike Samuel2013-04-23 03:23:24 +00:00Commented Apr 23, 2013 at 3:23
-
I believe the short answer is "not directly". Only code inside the function object can access local variables declared within the function object. However, for example if you create getters and setters inside the function object (that is "code inside the function object" too) and either set them as a property of another object OR return them, the function object's local variables will remain in memory and be accessible.orb– orb2013-04-23 03:42:17 +00:00Commented Apr 23, 2013 at 3:42
2 Answers
A closure is where code has access to variables in an outer execution context. In useful closures, a variable continues to exist after the function containing it has finished execution, e.g.
var x = (function() {
var outerA = 'A';
return function() {
return outerA;
}
}());
The inner function has access to outerA, i.e. outerA is on its scope chain. The inner function is assigned to x, so afterward it still has access to outerA:
alert(x()); // A
So closures don't limit scope, they are a consequence of it.
This feature of javascript can be used to emulate what a class–based language would call private members. It can also be used for inheritance, where multiple objects have access to the same set of values (objects, functions, primitives, whatever).
Comments
There is no inheritance in Javascript as such. We simply simulate inheritance by various means.
Closures in JS simply refer to the fact of functions retaining values of the variables in its scope. So yes, the value will be retained as long as you are talking about the same object & scope.
3 Comments
"Each constructor is a function that has a property named “prototype” that is used to implement prototype-based inheritance and shared properties". Clearly there is inheritance in javascript (which is an implementation of ECMAScript).