Reputation: 1331
Hey im new to javascript and i stumbled upon this code in javascript. I dont understand how can be methods increment and print defined inside function. Does that mean that create is an object?
function create() {
var counter = 0;
return {
increment: function () {
counter++;
},
print: function () {
console.log(counter);
}
}
}
var c = create();
c.increment();
c.print(); // 1
Upvotes: 2
Views: 670
Reputation: 413702
The function "create()" returns an object. The object it returns has two properties, "increment" and "decrement", both of which have functions as values. The functions operate on the variable "counter" defined in "create()".
Each call to "create()" instantiates a new context called a "closure". The context encloses a new copy of the "counter" variable. The objects returned from calls to "create()" thus have access to their own private "counter" instance.
Upvotes: 1
Reputation: 11542
The keyword for you is closure.
Closures in javascript are quite covered, e.g. in How do JavaScript closures work?.
Upvotes: 0