一段代碼說明原理:
/*類*/
function Obj(){
this.func1 = function(){
alert("func1");
};
}
var obj1 = new Obj();
Obj.func2 = function(){//添加類方法
alert("func2");
};
Obj.prototype.func3 = function(){//添加原型方法
alert("func3");
}
try{
obj1.func2();/*對象不能使用添加的類方法*/
}catch(e){
alert(e);//報錯
}
var obj2 = new Obj();
try{
obj2.func2();/*雖然,在添加類方法後再初始化的對象也不能使用添加的類方法*/
}catch(e){
alert(e);//報錯
}
try{
obj1.func3();/*對象能使用添加的原型方法*/
}catch(e){
alert(e);
}
try{
Obj.func2();/*添加的類方法需要使用類來調用*/
}catch(e){
alert(e);
}
/*總結:
在類定義後,想爲這個類的所有對象動態增加方法,可以使用添加類方法的方式實現。
*/