当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 在window.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 中的 在window.setTimeout方法中传送对象


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

setTimeout方法是js中的延时方法,很多js的bug,只需要使用该方法延时一下,就会自动解决了,简直就是万能药方,也是我比较喜欢使用的最后手段。其语法是:
window.setTimeout(expr,msec)
expr是执行字符串,在msec毫秒之后,就会作为js运行。我昨天才发现,原来expr也可以是一个函数,呵呵,用这个特性,就可以进行对象的传送了。
下面的代码实现了把函数foo1中的对象p,延时传送到函数foo2中的功能。
点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

现在很多框架其实都直接一种多投事件(它的实现原理也不复杂),一个多投事件本身,其实是是一个标准的函数,但是它一般有下述的方法。
MuEvent.add = function (func) { ... }
MuEvent.addMethod = function (instance, func) { ... }

当使用第一种方法时,在激活func这个事件处理函数时,使用MuEvent的当前实例为this对象;第二种则使用传入的instance作为this对象。

因此对于setTimeout来说,我们传统的方法要这样使用它来激活方法:
----------
function doTimer() {
obj1.call();
obj2.call();
}
setTimeout(doTimer, 1000);

而使用多投事件的代码就可以如下:
----------
var e = new MuEvent();
e.addMethod(obj1, obj1.call);
e.addMethod(obj2, obj2.call);
setTimeout(e, 1000);
----------

当然,你想要写得COOL一点,可以是这样:
----------
setTimeout(function() {
return new MuEvent(obj1, obj1.call, obj2, obj2.call);
}(), 1000);
----------

作为一点点介绍,我所做的Qomo是用这种形式来实现的MuEvent。象Atlas之类的框架,大多也采用类似的方法。