The this
of setInterval()
= window
.
If you have strict mode enabled in your script (something like 'use strict';
at the start of your script) it will be undefined
. For all intents and purposes you might wish to use the global scope of window
You can rewrite your function to access window like this:
setInterval(() => {
this.age++; // this refers to the person object
window.something = this.age;
}, 1000);
Also, you're not saving the setInterval ID so you can't clear it when the object is obsolete. It will remain in memory causing you potential memory leaks
function Person(){
this.age = 0;
this.kill = function() {window.clearInterval(this.interval);};
this.interval = setInterval(() => {
this.age++; // this refers to the person object
}, 1000);
}
So that when a Person is obsolete, you can kill() them, leaving no traces of them.