OOP and settimeout scope

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
 
M

Martin Honnen

function C(){
this.message = 'hi';
}
C.prototype.set = function(){
setTimeout(this.talk, 4000);
};

A closure can help
C.prototype.set = function () {
var thisC = this;
setTimeout(function () { thisC.talk(); }, 4000);
};
 
P

petermichaux

Martin said:
A closure can help
C.prototype.set = function () {
var thisC = this;
setTimeout(function () { thisC.talk(); }, 4000);
};

Martin,

Thanks. This is a lot simpler than what I found in google. Just what I
was looking for.

(Totally unrelated but I just discovered that the google groups reply
button now automatically quotes.)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top