Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  177] [ 1]  / answers: 1 / hits: 46554  / 15 Years ago, thu, july 9, 2009, 12:00:00

Why can't I use setTimeout in a javascript object?



Message = function () {

...
...

this.messageFactory = ...
this.feedbackTag = document.getElementById('feedbackMessages');

this.addInfo = function (message) {
var info = this.messageFactory.createInfo(message); // create a div
this.feedbackTag.appendChild(info);

setTimeout('this.feedbackTag.removeChild(info)', 5000);
// why in here, it complain this.feedbacktag is undefined ??????

};
}


Thanks for Steve`s Solution, now it will work if the code is as below...
because the 'this' before was actually pointing to the function within setTimeOut, it cannot rearch Message.



Message = function () {

...
...

this.messageFactory = ...
this.feedbackTag = document.getElementById('feedbackMessages');

this.addInfo = function (message) {
var info = this.messageFactory.createInfo(message); // create a div
this.feedbackTag.appendChild(info);

var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);

};
}


But why doesn`t it work if we do this:



Message = function () {

...
...

this.messageFactory = ...
this.feedbackTag = document.getElementById('feedbackMessages');
// public function
this.addInfo = function (message) {
var info = this.messageFactory.createInfo(message); // create a div
this.feedbackTag.appendChild(info);

delayRemove(info);

};
// private function
function delayRemove(obj) {
var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);
}
}

More From » settimeout

 Answers
-1

Try replacing this line:



setTimeout('this.feedbackTag.removeChild(info)', 5000);


with these two lines:



var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);


Note:



Never pass setTimeout a string, as this invokes eval (which you should only use when necessary). Instead, pass setTimeout a function reference (this can be an anonymous function).



Finally, always check that the this keyword is pointing to what you think it points to (see http://www.alistapart.com/articles/getoutbindingsituations).



Addressing Question 2:



I believe that for normal functions, this is set to the window object—regardless of where they are declared. So moving the code into a separate function wouldn't fix the problem.


[#99157] Monday, July 6, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;