为什么我不能在 JavaScript 对象中使用 setTimeout
?
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 ??????
};
}
感谢史蒂夫的解决方案,现在如果代码如下,它就可以工作了...... 因为前面的 this 实际上是指向 setTimeOut 中的函数,所以无法检索 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);
};
}
但是如果我们这样做为什么不起作用:
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);
注意:
永不通过setTimeout
一个字符串,因为这会调用 eval
(您应该仅在必要时使用它)。相反,传递 setTimeout
函数引用(可以是匿名函数)。
最后,请务必检查 this
关键字是否指向您认为它指向的内容(请参阅 http://www.alistapart.com/articles/getoutbindingsituations )。
解决问题 2:
我相信对于普通函数,this
被设置为 window
对象——无论它们在哪里声明。因此,将代码移至单独的函数中并不能解决问题。
关于javascript - 如何使用 "setTimeout"调用对象本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1101668/