sevenluck 2009-08-21
代码如下:
var MyClass=function(){ var AddNum=function(a,b){ return a+b; } var AddString=function(a,b){ return "I am here"+a+b; } this.Add=function(a,b){ if(typeof(a)=="number") return AddNum(a,b); else return AddString(a,b); } } var MyObj = new MyClass(); var X = MyObj.Add(5,6); var Y = MyObj.Add("A","FFFFFF"); alert(X); //结果:11 alert(Y); //结果:I am hereAFFFFFF
代码如下:
function BaseClass(){ this.Hello=function(){ return this.Say(); } } function MyClassA(){ this.Say=function(){ return "Hello"; } } function MyClassB(){ this.Say=function(){ return "This is MyClassB"; } } MyClassA.prototype = new BaseClass(); MyClassB.prototype = new BaseClass(); var ObjA = new MyClassA(); var XX = ObjA.Hello(); alert(XX); //结果:Hello var ObjB = new MyClassB(); var YY = ObjB.Hello(); alert(YY); //结果:This is MyClassB
代码如下:
// 通过函数的arguments属性实现重载 function add() { var sum = 0 ; for ( var i = 0 ; i < arguments.length; i ++ ) { sum += arguments[i]; } return sum; } function test() { alert(add()); alert(add( 1 , 2 )); alert(add( 1 , 2 , 3 )); }
代码如下:
下面这一句和subClass.prototype = new parentClass();等价 subClass.inherit(parentClass); // subClass.prototype.method = function() { // 子类重写了父类的方法 -- 去掉注释运行试试看 // alert("subClass method"); // } function test() { var obj = new subClass(); obj.method(); } 这样,子类中定义的method 就覆盖了从父类中继承来的method 方法了。这是你可能会问,如何在子类中调用父类的method方法呢?好的,看实现如下: // 为类添加静态方法inherit表示继承于某类 Function.prototype.inherit = function (baseClass) { for ( var p in baseClass.prototype) { this .prototype[p] = baseClass.prototype[p]; } } /* 参考文章:http://menjoy.javaeye.com/blog/127847 */ // js实现重写 function parentClass() { this .method = function () { alert( " parentClass method " ); } } function subClass() { var method = this .method; this .method = function () { method.call( this ); alert( " subClass method " ); } } subClass.prototype = new parentClass(); // subClass.inherit(parentClass); //这一句貌似和上一句subClass.prototype = new parentClass();等价,其实呢????(注释上一行,运行这一行看看) subClass.prototype.constructor = subClass; function test() { var obj = new subClass(); obj.method(); }