1

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());
1
  • inc and getCount are not members of the function returned by timer - they are "private" functions within the function returned by timer Commented Apr 27, 2017 at 5:10

2 Answers 2

1

return object wrongly declared.you could use like this

  1. Return not with function use on object.
  2. And you are using 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());

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

2 Comments

seeing as they use let - lets assume ES6 ... function timer(){ let count = 0; return { inc(){ count++; }, getCount(){ return count; } }; } ... or even function timer(){ let count = 0; return { inc: () => count++, getCount: () =>count }; }
Just to clarify, when functions are simply included in the return statement they are private and cannot be invoked outside the function that contains them. But when they are set as values in an object, they can be invoked outside the function that contains them. Does that sound right?
0

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());

Comments