要实现链式访问,关键是对象属性内嵌函数要返回一个对象,比如this当前对象,要链式访问的函数都作为该对象的属性绑定到其上,这样就可以通过点子运算符访问这个函数了。
要实现回调函数,关键是要将回调函数作为参数传进程序,程序内部需要运行该函数,如需传递参数,就在该函数内使用参数,这样回调的时候就可以取回单数。比如此处的回调函数是f,回调函数f内的参数为this,这样回调时function(data)里的data就相当于回调函数内的this。
function test(x,y){
this.w=x;
this.v=y;
c=w+v;
this.c=c;
this.done=function(f){
if(c>0){
console.log("done c:"+c);
f(this);
}
return this;
}
this.fail=function(f){
if(c<=0){
console.log("fail c:"+c);
f(this);
}
return this;
}
return this;
}
test(3,-100).done(function(data){alert(data.c)}).fail(function(data){alert(data.v)});