当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 在Javascript类中使用setTimeout

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

在Javascript类中使用setTimeout


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 201 ::
收藏到网摘: n/a

最近遇到了一道 Javascript 考题,内容如下:
尝试实现注释部分的 Javascript 代码,可在其他任何地方添加更多
代码(如不能实现,说明一下不能实现的原因):
var Obj = function(msg){
this.msg = msg;
this.shout = function(){
alert(this.msg);
}
this.waitAndShout = function(){
// 隔五秒钟后执行上面的 shout 方法
}
}
var testObj = new Obj("Hello,World!");
testObj.shout();坦白的说,之前我并没有在 Javascript 类中使用 setTimeout/setInterval 的经验,所以开始就很草率的认为这是无法实现的。但是经过深思熟虑以后发现是可以实现的。退一步说,隔五秒执行某段语句是非常容易实现的。比如不考虑别的因素,题目中的函数是可以这样写:
this.waitAndShout = function(){
setTimeout('this.shout()', 5000);
}在运行以后,谁都会意识到 this 这个变量是无法找到的。但是这是为什么呢,很快就可以意识到,其实 setTimeout/setInterval 是 window 对象的一个方法,所以也可以写成 window.setTimeout/window.setInterval,那么上述的 this.shout() 就非常可以容易理解为什么不能执行了,因为它实际上调用的是 window.shout() 。
知道了原因以后解决起来就非常的容易了,只要将对象绑定到 window 对象下就可以(我对 Javascript 有趣的对象机制感到兴奋)。那么,上述的函数再做一个小的修改:
this.waitAndShout = function() {
window.Obj = this;
setTimeout('Obj.shout()', 5000);
}这样就可以了。实际上
setTimeout('Obj.shout()', 5000);等价于

window.setTimeout('window.Obj.shout()', 5000);另外,之前我也想到将对象保存为数组,然后引用调用,代码如下:
function ObjectClass (property) {
this.property = property;
this.id = ObjectClass.cnt;
ObjectClass.objects[ObjectClass.cnt++] = this;
this.method = ObjectClass_method;
}
ObjectClass.cnt = 0;
ObjectClass.objects = new Array();
function ObjectClass_method () {
setTimeout('ObjectClass.objects[' + this.id + '].method();', 5000);
}
var obj1 = new ObjectClass('feelinglucky');
obj1.method();不过个人感觉还是上述第一种方法清晰得多。
后记,Javascript 看来的确还是很多需要谨慎对待的地方,尤其是对象机制。就犹如我之前所说的,Javascript 并不比其他语言要复杂,但是它也没有你想象中的简单。
PS:完成这道题目以后, Google 发现其他的兄弟早已经解决了此类的问题,比如这里还有这里,可以对比参考一下。

--------------------------------------------------------------------------------
更新,感谢 Sheneyan 兄弟的提醒,还有另外的一个办法就是通过 Closure(闭包) 来实现,代码如下:
var Obj = function(msg){
this.msg = msg;
this.shout = function() {
alert(this.msg);
this.waitAndShout();
}
var _self = this;
this.waitAndShout = function() {
setTimeout(function(){_self.shout()}, 5000);
}
}
var testObj = new Obj("Hello,World!");
testObj.shout();看来这道题已经不能再害人了 :^)