浅析JavaScript继承方式

开发 前端
面向对象的语言多数都支持继承,继承最重要的优点就是代码复用,从而构建大型软件系统。如果一个类能够重用另一个类的属性和或方法,就称之为继承。从这个角度来看看JavaScript的继承方式。

前段时间温故了下JavaScript 的写类方式,从这篇开始我们看看JavaScript 的继承方式。

面向对象的语言多数都支持继承,继承最重要的优点就是代码复用,从而构建大型软件系统。如果一个类能够重用另一个类的属性和或方法,就称之为继承。从这个角度来看看JS的继承方式。JS中继承方式与写类方式息息相关。不同的写类方式造成不同的继承方式。各种流行JavaScript库继承方式也各不相同。从最简单的复用开始。

1、构造函数方式写类,通过方法调用复制父类属性/字段到子类 实现继承

这里父类,子类都采用构造函数方式写,不用原型。子类调用父类函数来复制父类的属性。

  1. /**  
  2.  * 父类Polygon:多边形  
  3.  * @param {Object} sides  
  4.  */ 
  5. function Polygon(sides) {  
  6.     this.sides = sides;  
  7.     this.setSides = function(s) {this.sides=s;}  
  8. }  
  9.  
  10. /**  
  11.  * 子类Triangle:三角形  
  12.  */ 
  13. function Triangle() {  
  14.     this.tempfun = Polygon;//父类引用赋值给子类的一个属性tempfun  
  15.     this.tempfun(3);//调用  
  16.     delete this.tempfun;//删除该属性  
  17.     this.getArea = function(){};  
  18. }  
  19.  
  20. //new个对象   
  21. var tri = new Triangle();  
  22. console.log(tri.sides);//继承的属性  
  23. console.log(tri.setSides);//继承的方法  
  24. console.log(tri.getArea);//自有的方法  
  25.  
  26. //缺点是对于Triangle的实例对象用instanceof为父类Polygon时是false  
  27. console.log(tri instanceof Triangle);//true  
  28. console.log(tri instanceof Polygon);//false 

因为 JavaScript中具名函数的多种调用方式 ,子类还可以有以下的多种实现方式。只是在子类中调用父类方法不同而已。

  1. function Triangle() {  
  2.     Polygon.call(this,3); //call方式调用父类  
  3.     this.getArea = function(){};      
  4. }  
  5. function Triangle() {  
  6.     Polygon.apply(this,[3]); //apply方式调用父类  
  7.     this.getArea = function(){};  
  8. }  
  9. function Triangle() {  
  10.     var temp = new Polygon(3); //new方式调用父类  
  11.     for(atr in temp) { //全部复制给子类  
  12.         this[atr] = temp[atr];  
  13.     }     
  14.     this.getArea = function(){};  

这种方式的缺点是子类的实例对象用instanceof检查父类时总是false。这与java中继承"is a "的关系是违背的。

2、原型方式写类,原型方式继承

core JS自身的对象系统就是采用原型方式(prototype based)继承的。或者说core JS没有采用常见的类继承(class based)系统,而是使用原型继承来实现自己的对象系统。工作中我们也可以用原型方式来实现继承,代码复用以构建自己的功能模块。

  1. /**  
  2.  * 父类Polygon:多边形  
  3.  *   
  4.  */ 
  5. function Polygon() {}  
  6. Polygon.prototype.sides = 0;  
  7. Polygon.prototype.setSides = function(s) {this.sides=s;}  
  8.  
  9. /**  
  10.  * 子类Triangle:三角形  
  11.  */ 
  12. function Triangle() {}  
  13. Triangle.prototype = new Polygon(); //这是原型继承关键的一句  
  14. Triangle.prototype.getArea = function(){}  
  15.  
  16. //new个对象  
  17. var tri = new Triangle();  
  18. console.log(tri.sides);//继承的属性  
  19. console.log(tri.setSides);//继承的方法  
  20. console.log(tri.getArea);//自有方法  
  21.  
  22. //instanceof测试  
  23. console.log(tri instanceof Triangle);//true,表明该对象是三角形  
  24. console.log(tri instanceof Polygon);//true,表明三角形也是多边形 

虽然从输出可以看出子类继承了父类Polygon的属性sides和方法setSides,但sides是0,怎么会是三角形呢。还得调用下tri.setSides(3)使之成为三角形。这样似乎很不方便。不能传参数,即是原型方式的缺点。优点是正确的维护了"is a"的关系。

3、组合构造函数/原型方式写类,采用前面种方式继承

这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上。

  1. /**  
  2.  * 父类Polygon:多边形  
  3.  */ 
  4. function Polygon(sides) {  
  5.     this.sides = sides;  
  6. }  
  7. Polygon.prototype.setSides = function(s) {this.sides=s;}  
  8.  
  9. /**  
  10.  * Triangle 三角形  
  11.  * @param {Object} base 底  
  12.  * @param {Object} height 高  
  13.  */ 
  14. function Triangle(base,height) {  
  15.     Polygon.call(this,3);//复制父类属性给自己  
  16.     this.base = base;  
  17.     this.height = height;  
  18. }  
  19. Triangle.prototype = new Polygon();//复制父类方法给自己  
  20.  
  21. Triangle.prototype.getArea = function(){ //***定义自己的方法  
  22.     return this.base*this.height/2;  
  23. }  
  24.  
  25. //new个对象  
  26. var tri = new Triangle(12,4);  
  27. console.log(tri.sides);//继承的属性  
  28. console.log(tri.setSides);//继承的方法  
  29. console.log(tri.base);//自有属性  
  30. console.log(tri.height);//自有属性  
  31. console.log(tri.getArea);//自有方法  
  32.  
  33. //instanceof测试,表明正确的维护了"is a"的关系  
  34. console.log(tri instanceof Triangle);//true,表明该对象是三角形  
  35. console.log(tri instanceof Polygon);//true,表明三角形也是多边形 

#p#

这篇开始写几个工具函数实现类的扩展。每个工具函数都是针对特定的写类方式(习惯)。这篇按照构造函数方式写类:属性(字段)和方法都挂在this上。以下分别提供了个类,分别作为父类和子类。

  1. //  父类Person  
  2. function Person(nationality) {  
  3.     this.nationality = nationality;  
  4.     this.setNationality = function(n) {this.nationality=n;};  
  5.     this.getNationality = function() {return this.nationality;};  
  6. }  
  7.  
  8. // 类Man  
  9. function Man(name) {  
  10.     this.name = name;  
  11.     this.setName = function(n){this.name=n;};  
  12.     this.getName = function(){return this.name;};  

继承工具函数一

  1. /**  
  2.  * @param {Function} subCls 子类  
  3.  * @param {Function} superCls 父类  
  4.  * @param {Object} param 父类构造参数  
  5.  */ 
  6. function extend(subCls,superCls,param) {  
  7.     superCls.call(subCls.prototype,param);  

使用如下

  1. extend(Man,Person,'China');  
  2. var m = new Man('jack');  
  3. console.log(m.nationality);//China  
  4. console.log(m.setNationality('Japan'));  
  5. console.log(m.getNationality('Japan'));//Japan 

输出可以看到Man继承了Person的属性及所有方法。这种继承方式于java的很不一样哦,

  1. class Animal {  
  2.     int legs;     
  3.     Animal(int l) {  
  4.         legs = l;  
  5.     }  
  6.     int getLegs() {  
  7.         return legs;  
  8.     }  
  9. }  
  10. public class Person extends Animal{  
  11.     //属性(字段)  
  12.     String name;      
  13.     //构造方法(函数)  
  14.     Person(int legs, String name) {  
  15.         super(legs);//调用父类构造器  
  16.         this.name = name;  
  17.     }     
  18.     //方法  
  19.     String getName() {  
  20.         return this.name;  
  21.     }  
  22.     public static void main(String[] args) {  
  23.           
  24.         Person p = new Person(2,"jack");          
  25.         System.out.println(p.legs);  
  26.     }  

Java中,子类Person在自身构造方法中调用父类构造方法super(legs),创建对象的时候直接将父类构造参数legs:2传进去,不仅仅只传自己的name:jack。上面JavaScript继承是在extend时传父类构造参数(extend函数的第三个参数),而不是在new Man时将父类构造参数传过去。好,模拟Java来实现下extend,这里巧妙的在子类上暂存了父类引用。

继承工具函数二

  1. /**  
  2.  * @param {Function} subCls  
  3.  * @param {Function} superCls  
  4.  */ 
  5. function extend(subCls,superCls) {    
  6.     subCls.supr = superCls;  
  7. }  

还是以Person为父类,来实现子类Woman

  1. function Woman(nationality,name) {  
  2.     Woman.supr.call(this,nationality);//和java有点类似哦,在子类中调用父类构造器  
  3.     this.name = name;  
  4.     this.setName = function(n){this.name=n;};  
  5.     this.getName = function(){return this.name;};  
  6. }<br>extend(Woman,Person);<br> 

***,创建对象的方式和java也类似,即new的时候同时将父类构造参数(nationality:Japan)传进去。

  1. var w = new Woman('Japan','lily');  
  2. console.log(w.nationality);//Japan  
  3. w.setNationality('U.S.A');  
  4. console.log(w.getNationality());//U.S.A 

继承工具函数三

  1. /**  
  2.  * @param {Function} subCls  
  3.  * @param {Function} superCls  
  4.  */ 
  5. function extend(subCls,superCls) {  
  6.     subCls.prototype = new superCls();    

父类,按原型方式写,即属性和方法都挂在原型上。

  1. /**  
  2.  *  父类Person  
  3.  */ 
  4. function Person(){}  
  5. Person.prototype.nationality = 'China';  
  6. Person.prototype.getNationality = function() {return this.nationality;}  
  7. Person.prototype.setNationality = function(n) { this.nationality = n;} 

子类继承与父类

  1. function Man() {}  
  2. extend(Man,Person); 

继承父类的属性和方法后,再添加子类自有属性,方法

  1. Man.prototype.name = 'jack';  
  2. Man.prototype.getName = function() { return this.name;}  
  3. Man.prototype.setName = function(n) { this.name=n;} 

测试如下,

  1. var m = new Man();  
  2. console.log(m);  
  3. console.log(m instanceof Person); 

可以看到这种写类方式,继承方式完全采用原型机制。

#p#

继承工具函数四

这种方式是目前比较流行的,51ditu网站的开发就是按照这种模式的。

  1. /**  
  2.  * @param {Function} subCls 子类  
  3.  * @param {Function} superCls 父类  
  4.  */ 
  5. function extend(subCls,superCls) {    
  6.     //暂存子类原型  
  7.     var sbp = subCls.prototype;  
  8.     //重写子类原型--原型继承  
  9.     subCls.prototype = new superCls();  
  10.     //重写后一定要将constructor指回subCls  
  11.     subCls.prototype.constructor = subCls;  
  12.     //还原子类原型  
  13.     for(var atr in sbp) {  
  14.         subCls.prototype[atr] = sbp[atr];  
  15.     }  
  16.     //暂存父类    
  17.     subCls.supr = superCls;  

按 构造函数+原型 方式写类,即属性挂在this上,方法挂在prototype上。

  1. /**  
  2.  *  父类Person  
  3.  */ 
  4. function Person(nationality){  
  5.     this.nationality = nationality;  
  6. }  
  7. Person.prototype.getNationality = function() {return this.nationality;}  
  8. Person.prototype.setNationality = function(n) { this.nationality = n;}  
  9.  
  10. /**  
  11.  *  子类Man  
  12.  */ 
  13. function Man(nationality,name) {  
  14.     Man.supr.call(this,nationality); //很重要的一句,调用父类构造器  
  15.     this.name = name;  
  16. }  
  17. Man.prototype.getName = function() {return this.name;}  
  18. Man.prototype.setName = function(n) {this.name=n;} 

注意子类Man中要显示的调用父类构造器已完成父类的属性/字段拷贝。

extend调用,创建Man的实例

  1. extend(Man,Person);  
  2. var m = new Man('USA','jack');  
  3. console.log(m);  
  4. m.setName('lily');  
  5. console.log(m.name); 

继承工具函数五

  1. /**  
  2.  * @param {String} className  
  3.  * @param {String/Function} superClass  
  4.  * @param {Function} classImp  
  5.  */ 
  6. function $class(className, superClass, classImp){  
  7.     if(superClass === "") superClass = Object;  
  8.     var clazz = function(){  
  9.         return function(){  
  10.             if(typeof this.init == "function"){  
  11.                 this.init.apply(this, arguments);  
  12.             }  
  13.         };  
  14.     }();  
  15.     var p = clazz.prototype = new superClass();  
  16.     var _super = superClass.prototype;  
  17.     window[className] = clazz;  
  18.     classImp.apply(p, [_super]);  

定义父类Person

  1. /**  
  2.  * 父类 Person  
  3.  */ 
  4. $class('Person','',function(){  
  5.     this.init = function(name){  
  6.         this.name = name;  
  7.     };  
  8.     this.getName = function(){  
  9.         return this.name;  
  10.     };  
  11.     this.setName = function(name){  
  12.         this.name = name;  
  13.     }  
  14. }); 

子类Man

  1. /**  
  2.  * 子类 Man  
  3.  */ 
  4. $class('Man', Person, function(supr){  
  5.     this.init = function(name, age){  
  6.         supr.init.apply(this,[name]); // 该句很重要  
  7.         this.age = age;  
  8.     };  
  9.     this.getAge = function(){  
  10.         return this.age;  
  11.     };  
  12.     this.setAge = function(age){  
  13.         this.age = age;  
  14.     };  
  15. });  
  16. var m = new Man('Jack',25);  
  17. console.log(m.name); // Jack  
  18. console.log(m.age); // 25 

从输出看可以看到子类Man的确继承了父类的属性和方法。

原文链接:http://www.cnblogs.com/snandy/archive/2011/03/09/1977804.html

【编辑推荐】

  1. 如何编写高质量的Javascript代码
  2. 浅析JavaScript的写类方式
  3. JavaScript跨域总结与解决办法
  4. JavaScript版几种常见排序算法分享
  5. 10个令人惊奇的HTML5和JavaScript效果
责任编辑:陈贻新 来源: snandy的博客
相关推荐

2017-06-26 10:35:58

前端JavaScript继承方式

2011-03-07 09:41:10

JavaScript

2011-03-08 09:15:04

JavaScript

2009-09-25 14:12:16

Hibernate继承

2020-04-28 10:05:33

JavaScript继承前端

2012-02-14 09:45:02

JavaScript

2011-08-31 14:48:33

JavaScript

2010-01-21 13:48:30

C++基类

2011-08-24 13:56:27

JavaScript

2010-09-28 14:12:50

Javascript

2021-12-04 11:17:32

Javascript继承编程

2009-08-13 18:15:06

C#继承构造函数

2017-07-21 09:40:35

Python类、继承和多态

2009-06-17 14:55:26

Hibernate数据

2013-09-18 14:01:46

JavaScript

2009-09-07 05:24:22

C#窗体继承

2009-07-08 17:42:26

this属性

2011-05-25 16:23:35

Javascript类继承

2021-07-27 22:56:00

JavaScript编程开发

2009-07-14 11:34:42

MyEclipse断点JavaScript
点赞
收藏

51CTO技术栈公众号