问题描述
为什么我不能在javascript对象中使用 setTimeout
?
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 ??????
};
}
感谢Steve的解决方案,现在如果代码为低于...
,因为'this'之前实际上是指向setTimeOut中的函数,它无法重新发送消息。
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);
}
}
推荐答案
尝试替换此行:
setTimeout('this.feedbackTag.removeChild(info)', 5000);
这两行:
var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);
注意:
永远不要通过一个字符串,因为它调用 eval
(你应该只在必要时使用它)。而是通过功能引用(这可以是匿名函数)。
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).
最后,始终检查 this
关键字是否指向什么你认为它指向(参见) 。
Finally, always check that the this
keyword is pointing to what you think it points to (see http://www.alistapart.com/articles/getoutbindingsituations).
解决问题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.
这篇关于如何使用“setTimeout”调用对象本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!