Code:
var a = function() {
this.message = "hello";
this.shout = function(){
alert(this.message); // alerted undefined
}
this.Timer = setTimeout(this.shout, 3000);
}
var b = new a();
I get undefined in the alert dialog. I’ve tried “this.shout()” in setTimeout but then there is a DOM error on finding shout. How do I deal with this?
thisin your functionshoutrefers to the functionshout, rather than the functionaIf you define your variable in the scope of
ainstead of using this, you can refer to it later on and get it’s value:Or if you’d like you can store a reference instead, so that you can use self to refer to
a: