【发布时间】:2013-07-10 09:21:48
【问题描述】:
我编写了这个简单的类来创建一个带有消息的 div 元素,该消息应该在给定时间后消失。这很好用,但是当使用它创建多条消息时,隐藏和销毁功能将仅适用于最后创建的消息。
这是我的课:
function message(text, duration){
var self = this;
function init(){
this.obj = document.createElement("div");
this.obj.setAttribute("class", "message");
this.obj.appendChild(document.createTextNode(text));
document.body.appendChild(this.obj);
setTimeout(function(){self.display.call(this);}, 20);
setTimeout(function(){self.hide.call(this);}, duration);
setTimeout(function(){self.destroy.call(this);}, duration+1000);
}
this.display = function(){
this.obj.setAttribute("class", "message display");
}
this.hide = function(){
this.obj.setAttribute("class", "message gone");
}
this.destroy = function(){
document.body.removeChild(this.obj);
}
init();
}
这行得通:
new message("This will be removed in 5 seconds.", 5000);
这不起作用:
new message("This will not be shown", 2000);
new message("This will be removed after 2 seconds", 5000);
可能有一些参考错误,但我没有发现任何错误。
【问题讨论】:
-
在您的代码中包含jsfiddle 会很有用。
-
thisinsidesetTimeout可能不是你想的那样...... -
你有
var self = this来避免嵌套函数没有正确this的问题(这很好),但是你不使用self几乎只要你需要。也就是说:你有大量的this用法实际上是指window。因此,您的所有函数都在window.obj上运行,而不是在特定于实例的obj字段上运行。 -
这是一个有效的小提琴:jsfiddle.net/Dkf89
-
关于
self,你可以说self.display();,你不需要使用.call()来做self.display.call(this);(即使this是你当时所期望的,它不是)。
标签: javascript class dom object reference