I have been reading about closures and javascript, and I thought I got it, till I tried this:
var Object5 = function (param) {
var x = 0;
var squareBrace = function () {
return '[' + param + x + ']';
};
this.toString = function () {
x = x + 1;
return squareBrace();
};
};
Then I ran this code:
var counter = new Object5("Counter: ");
print("Has x:" + ('x' in counter));
print("Has f:" + ('f' in counter));
print("Can access x:" + (!!counter.x));
print("Can Invoke f:" + (!!counter.f));
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
And that is what I got:
Has x:false
Has f:false
Can access x:false
Can Invoke f:false
[Counter: 1]
[Counter: 2]
[Counter: 3]
[Counter: 4]
[Counter: 5]
[Counter: 6]
I thought I would get a ‘TypeError’ because ‘x’ and ‘f’ would be ‘undefined’, but then I got it working. I thought closures were for enable this behavior, ‘x’ and ‘y’ are ‘private’ and without a closure those member would be forgotten.
Apparently I got it all wrong, or I am missing something important here.
Could please somebody tell me what are closures for then and why this work?
Thanks.
A closure is a scoping technique. It’s a way of pulling a parameter defined in one scope into another scope. When you do
xwill be available in the function even though its not declared in the function.In your specific instance, 2 variables are closed-in:
paramandx. They are bound to the scope of the functions you defined. When you executetoString, your are incrementing the closed inx. WhentoStringexecutessquareBrace, that method uses bothxandparam. So you have 2 closures around the variablex, one for each method (its also in the scope of the object itself)