-2

When I try and run the add function it gives TypeError: this.add is not a function

function Timer(){
    this.t; 
    this.count = 0;

    this.start = function(){
        this.t = setInterval(function () {this.add()}, 1000);
    }
    this.add = function(){
        this.count++;
        console.log(this.count);
    }
}

function startTimer(){
    timer = new Timer();
    timer.start();
}

How am I able to access this.add function in that instance?

K3NN3TH
  • 1,458
  • 2
  • 19
  • 31
  • 2
    I'm reluctant to link to that other QA as it's full of answers which aren't the best one today. The accepted one, especially, wouldn't really help OP. – Denys Séguret May 22 '15 at 13:10

2 Answers2

3

A solution would be to create a variable to hold this but a simpler one is to use bind:

this.t = setInterval(this.add.bind(this), 1000);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

This happens because this inside your anonymous function get wrong context. You need to bind that function to your original context:

this.t = setInterval(function () {this.add()}.bind(this), 1000);

Or keep reference to your context inside some variable:

function Timer(){
    this.t; 
    this.count = 0;

    this.start = function(){
        var self = this;
        this.t = setInterval(function () {self.add()}, 1000);
    } 
...
antyrat
  • 27,479
  • 9
  • 75
  • 76