js链式编程

本文介绍了一种使用链式编程在JavaScript中动态扩展对象方法的技术,通过实例展示了如何添加、调用和链接自定义方法,实现对象功能的灵活扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js链式编程 实现对象方法动态扩展
(function(window){

window._MethodManager=function(obj)
{
//要处理的数据对象
this.data=obj;
//要添加的方法
this.methodNames=[];
}
//添加方法
_MethodManager.prototype.addMethod=function(name,fn)
{
//向原型链添加方法
_MethodManager.prototype[name]=fn;
//添加方法名称
this.methodNames.push(name);
return this;
}

})(window);

var fm=new _MethodManager("this is a data");
//添加方法一
fm.addMethod('methodone',function(){
var handdata=this.data;
//hand the data
this.data=this.data+" hand one ";
return this;
});
//添加方法2
fm.addMethod('methodtwo',function(){
var handdata=this.data;
//hand the data
this.data=this.data+" hand two ";
return this;
});

..添加其他的方法

console.dir(fm);
console.log(fm.methodone().data);
console.log(fm.methodone().methodtwo().data);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值