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

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

在Javascript类中使用setTimeout


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 219 ::
收藏到网摘: 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();看来这道题已经不能再害人了 :^)