Reputation: 50750
When using Javascript Closures, is there some difference in using Object literal Vs Constructor based objects ?
Are there just syntax difference OR is there some other difference as well for Closures? Any example explaining the 2 differences would be really helpful.
Upvotes: 0
Views: 663
Reputation: 74214
Closures are a feature of functional programming. They have nothing to do with objects or object literals.
Read the following answer - it explains closures really well: https://stackoverflow.com/a/12931785/783743
In general a closure is a function which closes over the variables in a nested function which moves out of the scope of the closure. For example:
function getCounter() {
var count = 0;
return function counter() {
return ++count;
};
}
var counter = getCounter();
counter(); // 1
counter(); // 2
counter(); // 3
Here the function getCounter
becomes a closure because it closes over the variable count
used in the nested function counter
when the nested function is returned (moves out of the scope of getCounter
).
The variable which is closed over (in this case count
) is called an upvalue. Closures are important because they allow values which would otherwise go out of scope (be garbage collected) to remain alive. This is not possible in languages like C/C++ and Java.
Upvotes: 1
Reputation: 7466
Closure is more about the function scope of the variable. So the important thing to know is that the scope of a variable is the function it was defined in. Any function that run inside this scope will have access to its parent function per se. Parent function won't have access to a child function variable, because it's outside of that child's scope.
Therefore a variable in an object literal, would be scoped to the function that it is contained it. (If it's not in a function, then it's in the global scope). A constructor is a function so any variables that it defines, is scoped in itself and inaccessible outside. Any inner methods that are in the constructor has access to those defined variables.
Closures are created when a function has access to a variable that is outside its own scope and that variable may be changed or altered by something else...even well after the function has finished execution.
I hope that helped some what.
Upvotes: 0