2

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
Armin
  • 15,582
  • 10
  • 47
  • 64
Aljoša Srebotnjak
  • 1,311
  • 2
  • 12
  • 13
  • You can use a service like the [online JavaScript beautifier](http://jsbeautifier.org) to clean up messy code. – Pointy Jan 09 '12 at 11:09

2 Answers2

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks for the answer and please forgive me for beginners questions, like i said im new to javascript. I have two subquestions for your answer - What is the object that function "create()" returns called or its name propherty, and what is the diference between functions like "create()" taht return object or functions that represent classes in javascript – Aljoša Srebotnjak Jan 10 '12 at 12:32
  • The object is not really called anything in particular; sometimes people call that an "object literal". And there's only one kind of function in JavaScript, as far as the language is concerned. Any function can be used as an object constructor, though what the function actually does may not make much sense for that. There are many different schemes for doing OOP in JavaScript, but the actual language mechanism is *not* very much like OOP in C++, C#, or Java. – Pointy Jan 10 '12 at 13:24
  • (Here in 2018 there are of course different kinds of functions.) – Pointy Feb 08 '18 at 17:00
0

The keyword for you is closure.

Closures in javascript are quite covered, e.g. in How do JavaScript closures work?.

Community
  • 1
  • 1
Krizz
  • 11,362
  • 1
  • 30
  • 43