使用场景:
由于网页中有大量的As与JS交互。As加载与初始化过程比较长。当As未初始化完成,JS开始调用会导致JS报错,影响后续JS的运行。
异步代码:
function Async(){
// 是否开始标记
this.isRead = false,
this.fs = new Array(), // this对象
// 准备好了
this.read = function() {
this.isRead = true;
for(var i = 0; i<this.fs.length; i++) {
this.execute(this.fs[i].o,this.fs[i].f,this.fs[i].p,this.fs[i].r)
}
this.reInit();
},
// 对象初始化
this.reInit = function() {
this.fs = new Array(); // this对象
},
// 代理调用函数
this.proxy = function(obj,fc,params,reFc){
if(this.isRead) {
this.execute(obj,fc,params,reFc);
return;
}
// 将函数与对应参与放到对象内
this.fs[this.fs.length] = {
"o":obj,
"f":fc,
"p":params,
"r":reFc
}
},
// 执行
this.execute = function(obj,fc,params,reFc) {
var result = fc.apply(obj, params);
if(reFc) {
reFc.apply(this, [result]);
}
}
}
使用示例:
// 测试代码
//测试对象
var t = {
g1:function(v){
console.log("g1:目标方法,传递参数:%O",v);
return v;
},
g2:function(v) {
console.log("g2:回调方法,返回:" + v);
}
};
// 使用对象
var a = new Async();
a.proxy(t,t.g1,["这是测试"],t.g2);
a.read();