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
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
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.
(Here in 2018 there are of course different kinds of functions.)
0

The keyword for you is closure.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.