+ 1

Why count gives unexpected value. Please read the description. Its hard to describe the question in one line.

// I am putting my code to make my question easier to understand. After the code, I put my question let counter = (function() { let count = 1; function print(message) { console.log(message + '---' + count); } // return an object return { value: count, increment: function() { count += 1; print('Afer increment: '); }, reset: function() { print('Before reset: '); count = 1; print('After reset: '); } }; })(); console.log(counter.value); //Output: 1 counter.increment(); // Output: After increment ---2 counter.increment(); // Output: After increment ---3 console.log(counter.value); //Output: 1 (line 31) counter.reset(); //Output Before reset: --3 After reset ---1 (line 32) Q. Why does line 31 gives '1' instead of '3'. And again why does line 32 give 'before reset --3' instead of 'before reset --1'? - As property 'value' takes the data of 'count' I thought counter.value will output 3 after incrementing twice from its initial value 1 but didn't. Instead, it still outputs its initial value 1. So I call the reset method and thought it will output 'Before output: 1' as counter.value gives 1 but instead gives 'Before increment: 3'. Why is this happening?

16th Jul 2018, 10:09 AM
RanjOyHunTer
RanjOyHunTer - avatar
2 Antworten
+ 2
Because you return an object with key's value of 1 and key (method increment) which do nothing until you call it. So, when calling counter.value, the count is reseted to 1. Try to declare and assign the count outer any function (in the global scope).
16th Jul 2018, 10:36 AM
Boris Batinkov
Boris Batinkov - avatar
+ 1
Try to create getter for count Please check https://code.sololearn.com/W6tqESssflaa/?ref=app
16th Jul 2018, 11:04 AM
Calviղ
Calviղ - avatar