Reputation: 224
closures have an access of outerfunction , global and inner function scope. It is an function bundled up together and will be able to return an function. so this is the counter example build with closures
function outerfunction() {
var y = 10;
return {
add() {
y = y + 1;
console.log(y)
},
sub() {
console.log(y)
y = y - 1;
},
value() {
return y;
}
}
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12
console.log(counter.value()); //12
counter.sub(); //11
counter.sub(); //10
console.log(counter.value()); //10
And this is the normal function for counter example, even in this functions has access to outside function scope,global scope and inner function scope. So what is the difference. here is the below code.
var counter = 10;
const add = () => {
console.log(counter);
counter++;
}
const sub = () => {
console.log(counter);
counter--;
}
console.log(counter); //10
add(); //11
add(); //12
console.log(counter); //12
sub(); //11
sub(); //10
console.log(counter); //10
Please correct if i am wrong. Thanks in advance
Upvotes: 0
Views: 402
Reputation: 780889
The difference is that you can make multiple closures, and they each will have their own y
variable saved.
function outerfunction() {
var y = 10;
return {
add() {
y = y + 1;
console.log(y)
},
sub() {
console.log(y)
y = y - 1;
},
value() {
return y;
}
}
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12
const counter2 = outerfunction();
console.log(counter2.value()); //10
counter2.sub(); //9
counter2.sub(); //8
console.log(counter2.value()); //9
When you use a global variable, there's only one counter.
Upvotes: 2
Reputation: 138267
Well actually every function has a reference to its parent function's environment record (where all the variables reside in). In your second example that environment record is the global scope, in the first example it's the one from the outerFunction call. So there is no difference and there's no such a thing as a closure. That term is just used to describe the resulting behaviour.
Upvotes: 1