P
petermichaux
Hi,
I've been searching google and the archives here but haven't found a
clear solution. I want to do something like the following
function C(){
this.message = 'hi';
}
C.prototype.set = function(){
setTimeout(this.talk, 4000);
};
C.prototype.talk = function(){
alert(this.message);
};
This doesn't do what I want, of course. I understand that when the
"talk" method runs the "this" won't be the same "this" as when the
"set" method runs. I would like the two "this" references to mean the
same instance of C and not the window. Is there a simple solution?
If closures are the solution is there a way to avoid moving the method
definititions into the constructor? That seems like cluttering the
constructor to me. But if that is the simplest it is ok too.
Thanks,
Peter
I've been searching google and the archives here but haven't found a
clear solution. I want to do something like the following
function C(){
this.message = 'hi';
}
C.prototype.set = function(){
setTimeout(this.talk, 4000);
};
C.prototype.talk = function(){
alert(this.message);
};
This doesn't do what I want, of course. I understand that when the
"talk" method runs the "this" won't be the same "this" as when the
"set" method runs. I would like the two "this" references to mean the
same instance of C and not the window. Is there a simple solution?
If closures are the solution is there a way to avoid moving the method
definititions into the constructor? That seems like cluttering the
constructor to me. But if that is the simplest it is ok too.
Thanks,
Peter