I am trying to access variables from the constructor inside a sub-function of a prototype defined function. I understand that this.variable
can access constructor variables in prototype functions but it cannot be accessed from another function inside.
function MyObject() {
this.message = "Hello world!";
}
MyObject.prototype = {
sayHello: function() {
console.log(this.message);
},
repeatHello: function() {
setInterval(function() {
this.sayHello();
}, 1000);
}
}
let test = new MyObject();
// test.sayHello();
test.repeatHello();
With the example above, since I am calling this
in the new function it makes sense it can't read the functions and variables outside of it since they are not defined to that function. How do I get access to sayHello()
or this.message
from the sub-function?