Answer the question
In order to leave comments, you need to log in
How to solve the problem with the "module" pattern (JavaScript)?
let Test = function() {
let i = 0;
return {
inc() {
i++;
},
cur() {
return i;
}
};
};
let myTest1 = Test();
myTest1.inc();
console.log(myTest1.cur());
myTest1.inc();
console.log(myTest1.cur());
myTest1.inc();
console.log(myTest1.cur());
let myTest2 = Test();
myTest2.inc();
console.log(myTest2.cur());
//Вот этот способ не работает. Почему?
//Test().inc();
//Test().inc();
//Test().inc();
//console.log(Test().cur());
Answer the question
In order to leave comments, you need to log in
Well, obviously, in the first case, you create a variable and a place is allocated in memory for it and your "module" exists, so you can increment and print its value. In the second case, you simply call the method and that's it, the function is not stored anywhere in memory - it is simply collected by the garbage collector, because. There are no more links to it. (The first call creates a closure and saves it, the second call doesn't save the closure)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question