没有合适的资源?快使用搜索试试~ 我知道了~
一、方法体内返回对象实例自身(this) 代码如下: function ClassA(){ this.prop1 = null; this.prop2 = null; this.prop3 = null; } ClassA.prototype = { method1 : function(p1){ this.prop1 = p1; return this; }, method2 : function(p2){ this.prop2 = p2; return this; }, method3 : function(p3){ this.prop3 = p3; return this; } }
资源推荐
资源详情
资源评论













JavaScript中两种链式调用实现代码中两种链式调用实现代码
一、方法体内返回对象实例自身一、方法体内返回对象实例自身(this)
代码如下:
function ClassA(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
ClassA.prototype = {
method1 : function(p1){
this.prop1 = p1;
return this;
},
method2 : function(p2){
this.prop2 = p2;
return this;
},
method3 : function(p3){
this.prop3 = p3;
return this;
}
}
定义了function/类ClassA。有三个属性/字段prop1,prop2,prop3,三个方法methed1,method2,method3分别设置
prop1,prop2,prop3。
链式调用如下:
代码如下:
var obj = new ClassA();
obj.method1(1).method2(2).method(3); // obj -> prop1=1,prop2=2,prop3=3
可以看到对obj进行了连续三次操作,只要愿意ClassA的N多方法都这样定义,调用链会一直延续。
该方式缺点是链方法唯一地绑定于一种对象类型(ClaaaA),按这种方式实现链式操作,每定义一个类,其方法体中都要返回
this。第二种方式可以解决这个问题。
二、对象传入后每次调用返回函数自身二、对象传入后每次调用返回函数自身
代码如下:
/**
* chain 精简版
* @param {Object} obj
*/
function chain(obj){
return function(){
var Self = arguments.callee; Self.obj = obj;
if(arguments.length==0){
return Self.obj;
}
Self.obj[arguments[0]].apply(Self.obj,[].slice.call(arguments,1));
return Self;
}
}
//定义的function/类ClassB
function ClassB(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
ClassB.prototype = {
method1 : function(p1){
this.prop1 = p1;
},
method2 : function(p2){
this.prop2 = p2;
},
method3 : function(p3){
this.prop3 = p3;
}
}
资源评论


weixin_38735119
- 粉丝: 7
- 资源: 876
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


安全验证
文档复制为VIP权益,开通VIP直接复制
