user7839191
user7839191

Reputation:

Implementing simple callback in JS

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

Answers (2)

taile
taile

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

prasanth
prasanth

Reputation: 22490

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

Upvotes: 1

Related Questions