joj*_*ojo 24 javascript settimeout
为什么我不能setTimeout
在javascript对象中使用?
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 ??????
};
}
Run Code Online (Sandbox Code Playgroud)
感谢Steve的解决方案,现在如果代码如下所示它将起作用...因为之前'this'实际指向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);
var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);
};
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我们这样做,为什么它不起作用:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*son 84
尝试替换此行:
setTimeout('this.feedbackTag.removeChild(info)', 5000);
Run Code Online (Sandbox Code Playgroud)
有这两行:
var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);
Run Code Online (Sandbox Code Playgroud)
注意:
永远不要传递setTimeout
一个字符串,因为这会调用eval
(只有在必要时才能使用).相反,传递setTimeout
一个函数引用(这可以是一个匿名函数).
最后,请始终检查this
关键字是否指向您认为指向的内容(请参阅http://www.alistapart.com/articles/getoutbindingsituations).
解决问题2:
我相信对于普通函数,this
设置为window
对象 - 无论它们在何处被声明.因此,将代码移动到单独的函数中无法解决问题.
一种更简洁的方法是将此作为参数传递给超时中调用的函数:
function delayRemove(obj) {
setTimeout(function(_this) {
_this.feedbackTag.removeChild(obj);
}, 5000, this);
}
Run Code Online (Sandbox Code Playgroud)
你应该将obj作为参数传递,只是为了确保它在范围内(参数的数量是无限的):
function delayRemove(obj) {
setTimeout(function(_this, removeObj) {
_this.feedbackTag.removeChild(removeObj);
}, 5000, this, obj);
}
Run Code Online (Sandbox Code Playgroud)
HTML5和Node.js扩展了setTimeout
函数以接受传递给回调函数的参数.它具有以下方法签名.
setTimeout(callback, delay, [param1, param2, ...])
由于setTimeout
实际上不是JavaScript功能,因此您的搜索结果可能因浏览器而异.我找不到任何具体的支持细节,但正如我所说,这是HTML5规范.
归档时间: |
|
查看次数: |
43231 次 |
最近记录: |