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