1

Can someone tell me why setInterval isn't working in this code. I might be missing something and I am not sure what it is. I am trying to run the method args.counts();

Error is:

Uncaught TypeError: this.cast is not a function at Caste.log (prototype.js:17)

    function Caste(){
    this.name = 'James';
    this.surname = 'Penn';
    this.age = 38;

    this.one = document.getElementById('one');
    this.two = document.getElementById('two');

    this.cast = function(){
         return  this.age;
    }
    // ------------------------

    this.log = function(){
        console.log(this.cast());
    }
    // ------------------------
    this.display = function(){
        this.one.innerHTML = this.age;
    }

    this.counts = function(){
     (setInterval(this.log, 2000));
    }
}

// ----------------------

let args = new Caste();
args.counts();
4b0
  • 21,981
  • 30
  • 95
  • 142

1 Answers1

1

setInterval is shorthand for window.setInterval, which means that the calling context is window, rather than the instantiated object. Either bind the function to the instantiated object:

(setInterval(this.log.bind(this), 2000));

Or use an arrow function:

(setInterval(() => this.log(), 2000));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Excellent. I hope the moderator would leave this thread. From the viewpoint of a newbie, this looks like a different approach to the answer. – Kingsley Ajebon May 14 '18 at 08:53