Reputation:
I am trying to learn callbacks in JS, and I do not understand why the following code will not work:
function timer(){
let count = 0;
return function (){
function inc(){
count++;
}
function getCount(){
return count;
}
}
}
let t = timer();
t.inc();
t.inc();
t.inc();
console.log(t.getCount());
Upvotes: 1
Views: 60
Reputation: 2776
Because you timer function return a function but inside it doesn't return anything
Here is the correction
function timer(){
let count = 0;
return {
inc :function(){
count++;
},
getCount :function (){
return count;
}}
}
let t = timer();
t.inc();
t.inc();
t.inc();
console.log(t.getCount());
Upvotes: 0
Reputation: 22490
return
object wrongly declared.you could use like this
inc
and getcount
are private function is not with in return object function.so its not returning.function timer() {
let count = 0;
return {
inc : function() {
count++;
},
getCount : function() {
return count;
}
}
}
let t = timer();
t.inc();
t.inc();
t.inc();
console.log(t.getCount());
Upvotes: 1