javascript面向对象三大特征之继承实例详解(3)

function A(x,y){ this.x = x; this.y = y; } A.prototype.add = function(){ return (this.x-0) + (this.y-0); } function B(x,y){ A.call(this,x,y); } B.prototype = new A(); // 测试 var b = new B(2,1); console.log(b.x); // 2 console.log(b.add()); // 3

多重继承

继承一般包括单向继承和多向继承,单向继承模式较为简单,每个子类有且仅有一个超类,多重继承是一个比较复杂的继承模式。一个子类可拥有多个超类。JavaScript原型继承不支持多重继承,但可通过混合模式来实现多重继承。下面让类C来继承类A和类B:

function A(x){ this.x = x; } A.prototype.hi = function(){ console.log('hi'); } function B(y){ this.y = y; } B.prototype.hello = function(){ console.log('hello'); } // 给Function增加extend方法 Function.prototype.extend = function(obj) { for(var item in obj) { this.constructor.prototype[item] = obj[item]; } } // 在类C内部实现继承 function C(x,y){ A.call(this,x); B.call(this,y); }; C.extend(new A(1)); C.extend(new B(2)); // 通过复制继承后,C变成了一个对象,不再是构造函数了,可以直接调用 C.hi(); // hi C.hello(); // hello console.log(C.x); // 1 console.log(C.y); // 2

一个类继承另一个类会导致他们之间产生耦合,在js中提供多种途径来避免耦合的发生如 掺元类

掺元类是一种比较特殊的类,一般不会被实例化或者调用,定义掺元类的目的只是向其他类提供通用的方法。

// 定义一个掺元类 function F(x,y){ this.x = x; this.y = y; } F.prototype = { getx:function(){ return this.x; }, gety:function(){ return this.y; } } // 原型拷贝函数 function extend(Sub,Sup){ // Sub 子类 , Sup 掺元类 for(var item in Sup.prototype){ if(!Sub.prototype[item]){ // 如果子类没有存在同名成员 Sub.prototype[item] = Sup.prototype[item]; // 那么复制掺元类成员到子类原型对象中 } } } // 定义两个子类 A,B function A(x,y){ F.call(this,x,y); } function B(x,y){ F.call(this,x,y); } // 调用extend函数实现原型属性,方法的拷贝 extend(A,F); extend(B,F); console.log(A.prototype); // 测试继承结果 var a = new A(2,3); console.log(a.x); // 2 console.log(a.getx()); // 2 console.log(a.gety()); // 3 var b = new B(1,2); console.log(b.x); // 1 console.log(b.getx()); // 1 console.log(b.gety()); // 2

通过此种方式把多个子类合并到一个子类中,就实现了多重继承。

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具测试上述代码运行效果。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/83241ceae06385859fb36d02526a3c05.html