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

被折叠的 条评论
为什么被折叠?



