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
-
You can use a service like the online JavaScript beautifier to clean up messy code.Pointy– Pointy2012年01月09日 11:09:24 +00:00Commented Jan 9, 2012 at 11:09
2 Answers 2
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.
3 Comments
The keyword for you is closure.
Closures in javascript are quite covered, e.g. in How do JavaScript closures work?.