javaScript的类型函数(如Number/String/Boolean/Array/Date/Obejct等)都是继承于 Function.prototype,所以给Function.prototype增加方法,同时也会影响到由它衍生的下层类型函数。如:
复制代码 代码如下:
Function.prototype.addMethod=function(methodName,func){
if(!this[methodName]){
this[methodName]=func;//给类型增加方法,类似于类型的静态方法。func方法是赋于了类型而非实例。
}
return this;//this 将绑定到方法的调用对象(类型函数),返回this可以进行链式调用
}
Array.addMethod('testFun',function(){alert(this)});
//Array.testFun(); //function Array() {[native code]}
Object.addMethod('testFun',function(){alert(this)});
//Object.testFun(); //function Object() {[native code]}
Boolean.addMethod('testFun',function(){alert(this)});
//Boolean.testFun(); //function Boolean() {[native code]}
function CustomObject(name,value){
this.name=name || 'CustomObject';
this.value=value || 0;
this.toString=function(){return '[name:'+this.name+',value:'+this.value+']'}
}
CustomObject.addMethod('testFun',function(){alert(this)});
/* return:
* function CustomObject(name, value) {
this.name = name || "CustomObject";
this.value = value || 0;
this.toString = function () {return "[name:" + this.name + ",value:" + this.value + "]";};
}
*/
CustomObject.testFun();
此时如果用实例来调用的话,则会报错。如:
复制代码 代码如下:
var customObject=new CustomObject(); //定义一个CustomObject实例
customObject.testFun();//Error: temp.testFun is not a function
给实例增加方法
如果给类型实例增加方法,则应该把方法绑定到类型的prototype上。如
复制代码 代码如下:
Function.prototype.addMethod=function(methodName,func){
if(!this.prototype[methodName]){
this.prototype[methodName]=func;//给原型增加方法,此方法会影响到该类型的实例上
}
return this.prototype;//返回原型,此类型实例可以进行链形调用
}
Object.addMethod('testFun',function(){alert(this)});
//({toString:function(){return '[Empty Object]'}}).testFun(); //[Empty Object]
Number.addMethod('testFun',function(){alert(this)});
//(5).testFun(); //5
String.addMethod('testFun',function(){alert(this)});
//'test'.testFun(); //'test'
Boolean.addMethod('testFun',function(){alert(this)});
//true.testFun(); //true
Array.addMethod('testFun',function(){alert(this)});
//(['a','b']).testFun(); //a,b
Date.addMethod('testFun',function(){alert(this)});
//new Date().testFun(); //Tue Dec 27 2011 11:20:58 GMT-0800 (Pacific Standard Time)
function CustomObject(name,value){
this.name=name || 'CustomObject';
this.value=value || 0;
this.toString=function(){return '[name:'+this.name+',value:'+this.value+']'}
}
CustomObject.addMethod('testFun',function(){alert(this)});
var customObject=new CustomObject();
customObject.testFun(); //[name:CustomObject,value:0]
若此时用类型调用testFun,则会报错。如
复制代码 代码如下:
Array.addMethod('testFun',function(){alert(this)});
//Array.testFun(); //Error: Array.testFun is not a function
CustomObject.addMethod('testFun',function(){alert(this)});
CustomObject.testFun(); //Error: CustomObject.testFun is not a function