一、前言

最近在项目中,前端框架使用JavaScript面向对象编程,遇到了诸多问题,其中最典型的问题就是子类调用父类(super class)同名方法,也就是如C#中子类中调用父类函数base.**。以下摘录了园友幻天芒对JavaScript实现继承的几种方式 的具体介绍以作备忘。

二、JavaScript实现继承的几种方式

既然要实现继承,那么我们首先得有一个基类,代码如下:

  1. // 定义一个动物类
  2.     function Animal(name) {
  3.         // 属性
  4.         this.name = name || 'Animal';
  5.         // 实例方法
  6.         this.sleep = function () {
  7.             console.log(this.name + '正在睡觉!');
  8.         }
  9.     }
  10.     // 原型方法
  11.     Animal.prototype.eat = function (food) {
  12.         console.log(this.name + '正在吃:' + food);
  13.     };

1、原型链继承

核心: 将父类的实例作为子类的原型

  1. //定义动物猫
  2. function Cat() {
  3. }
  4. Cat.prototype = new Animal();
  5. Cat.prototype.name = 'cat';
  6. // Test Code
  7. var cat = new Cat();
  8. console.log(cat.name); //cat
  9. cat.eat('fish'); //cat正在吃:fish
  10. cat.sleep(); //cat正在睡觉
  11. console.log(cat instanceof Animal); //true
  12. console.log(cat instanceof Cat); //true

特点:

1.非常纯粹的继承关系,实例是子类的实例,也是父类的实例;

2.父类新增原型方法/原型属性,子类都能访问到;

3.简单,易于实现;

缺点:

1.要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中

2.无法实现多继承;

3.创建子类时,无法向父类构造函数传参;

4.来自原型对象的属性是所有实例所共享;

2、构造继承

核心:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)

  1. function Cat(name) {
  2.     Animal.call(this);
  3.     this.name = name || 'Tom';
  4. }
  5. // Test Code
  6. var cat = new Cat();
  7. console.log(cat.name);
  8. console.log(cat.sleep());
  9. console.log(cat instanceof Animal); // false
  10. console.log(cat instanceof Cat); // true

特点:

1. 解决了1中,子类实例共享父类引用属性的问题;

2. 创建子类实例时,可以向父类传递参数;

3. 可以实现多继承(call多个父类对象);

缺点:

1. 实例并不是父类的实例,只是子类的实例;

2. 只能继承父类的实例属性和方法,不能继承原型属性/方法;

3. 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能;

3、实例继承

核心:为父类实例添加新特性,作为子类实例返回

  1. function Cat(name) {
  2.     var instance = new Animal();
  3.     instance.name = name || 'Tom';
  4.     return instance;
  5. }
  6. // Test Code
  7. var cat = new Cat();
  8. console.log(cat.name);
  9. console.log(cat.sleep());
  10. console.log(cat instanceof Animal); // true
  11. console.log(cat instanceof Cat); // false

特点:

1. 不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果;

缺点:

2.无法实现多继承;

4、拷贝继承

  1. function Cat(name) {
  2.     var animal = new Animal();
  3.     for (var p in animal) {
  4.         Cat.prototype[p] = animal[p];
  5.     }
  6.     Cat.prototype.name = name || 'Tom';
  7. }
  8. // Test Code
  9. var cat = new Cat();
  10. console.log(cat.name);
  11. console.log(cat.sleep());
  12. console.log(cat instanceof Animal); // false
  13. console.log(cat instanceof Cat); // true

特点:

1. 支持多继承;

缺点:

1. 效率较低,内存占用高(因为要拷贝父类的属性);

2. 无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到);

5、组合继承

核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用

  1. function Cat(name) {
  2.     Animal.call(this);
  3.     this.name = name || 'Tom';
  4. }
  5. Cat.prototype = new Animal();
  6. Cat.prototype.constructor = Cat;
  7. // Test Code
  8. var cat = new Cat();
  9. console.log(cat.name);
  10. console.log(cat.sleep());
  11. console.log(cat instanceof Animal); // true
  12. console.log(cat instanceof Cat); // true

特点:

1.弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法;

2.既是子类的实例,也是父类的实例;

3.不存在引用属性共享问题;

4.可传参;

5.函数可复用;

缺点:

1. 调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了);

6、寄生组合继承

核心:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点

  1. function Cat(name){
  2.     Animal.call(this);
  3.     this.name = name || 'Tom';
  4. }
  5. (function(){
  6.     // 创建一个没有实例方法的类
  7.     var Super = function(){};
  8.     Super.prototype = Animal.prototype;
  9.     //将实例作为子类的原型
  10.     Cat.prototype = new Super();
  11.     Cat.prototype.constructor = Cat; // 需要修复下构造函数
  12. })();
  13. // Test Code
  14. var cat = new Cat();
  15. console.log(cat.name);
  16. console.log(cat.sleep());
  17. console.log(cat instanceof Animal); // true
  18. console.log(cat instanceof Cat); //true

特点:

1. 堪称完美;

缺点:

1.实现较为复杂;

三、实现子类调用父类方法的解决方案

上述的几种继承方式,如要实现子类Cat,在eat方法中调用父类Animal的eat方法,该如何实现呢? 以寄生组合继承为例:

  1. // 定义一个动物类
  2. function Animal(name) {
  3.     // 属性
  4.     this.name = name || 'Animal';
  5.     // 实例方法
  6.     this.sleep = function () {
  7.         console.log(this.name + '正在睡觉!');
  8.     }
  9. }
  10. // 原型方法
  11. Animal.prototype.eat = function (food) {
  12.     console.log("Father." + this.name + '正在吃:' + food);
  13. };
  14. function Cat(name) {
  15.     Animal.call(this);
  16.     this.name = name || 'Tom';
  17. }
  18. (function () {
  19.     // 创建一个没有实例方法的类
  20.     var Super = function () { };
  21.     Super.prototype = Animal.prototype;
  22.     //将实例作为子类的原型
  23.     Cat.prototype = new Super();
  24.     Cat.prototype.constructor = Cat; // 需要修复下构造函数
  25.     Cat.prototype.eat = function (food) {
  26.         console.log("SubClass." + this.name + '正在吃:' + food);
  27.         Super.prototype.eat.apply(this, Array.prototype.slice.apply(arguments));
  28.     };
  29. })();
  30. // Test Code
  31. var cat = new Cat();
  32. console.log(cat.name);
  33. cat.eat('fish'); //cat正在吃:fish
  34. console.log(cat instanceof Animal); // true
  35. console.log(cat instanceof Cat); //true

测试结果:

其中的关键代码在于:

我们看到,子类要想调用父类的方法,必须使用父类原型方法的apply(Super.prototype.eat.apply), 也就是必须得在子类中使用父类对象,这种以硬编码方式的调用,虽然能解决问题,但确不是特别优雅。

四、优化后的子类调用父类方法的实现方式

以上的继承方式,都不能实现子类调用父类方法, 在重写子类原型函数后,会将继承父类函数给覆盖。先来看实例:

父类:

  1. var Animal = Class.extend({
  2.     construct: function (name) {
  3.         arguments.callee.father.construct.call(this);
  4.         this.name = name || "Animal";
  5.     },
  6.     eat: function (food) {
  7.         console.log("Father." + this.name + '正在吃:' + food);
  8.     },
  9.     sleep: function () {
  10.         console.log("Father." + this.name + '正在睡觉!');
  11.     }
  12. });

子类:

  1. var Cat = Animal.extend({
  2.     construct: function () {
  3.         arguments.callee.father.construct.call(this,"Cat");
  4.     },
  5.     eat: function (food) {
  6.         console.log("SubClass." + this.name + '正在吃:' + food);
  7.         arguments.callee.father.eat.call(this, food);
  8.     },
  9.     sleep: function () {
  10.         console.log("SubClass." + this.name + '正在睡觉!');
  11.         arguments.callee.father.sleep.call(this);
  12.     }
  13. });

测试代码:

  1. // Test Code
  2. var cat = new Cat();
  3. console.log(cat.name);
  4. console.log(cat.eat('fish'));
  5. console.log(cat.sleep());
  6. console.log(cat instanceof Animal); // true
  7. console.log(cat instanceof Cat); //true

输出结果:

在实例中,我们看到cat实例对象,在eat函数中,既调用了Cat类的eat函数,也调用了Animal类的eat函数,实现了我们想要达到的效果。实现该种继承的关键点在于Class基类中的处理,为子类每个function对象,都添加了father属性,指向父类的原型(prototype)

优化的设计,它使用了JavaScript中一点鲜为人知的特性:callee。
在任何方法执行过程中,你可以查看那些通过"arguments"数组传入的参数,这是众所周知的,但很少有人知道"arguments"数组包含一个名为"callee"的属性,它作为一个引用指向了当前正在被执行的function,而后通过"father"便可以方便的获得当前被执行function所在类的父类。这是非常重要的,因为它是获得此引用的唯一途径(通过"this"对象获得的function引用总是指向被子类重载的function,而后者并非全是正在被执行的function)。

这种实现方式类似于C#中base.**的用法调用,而不需要在子类中出现父类名称的硬编码,但也存在缺点,不能够实现多继承。

五、总结

附录一、Class基类

  1. //定义最顶级类,用于js继承基类
  2. function Class() { }
  3. Class.prototype.construct = function () { };
  4. Class.extend = function (def) {
  5.     var subClass = function () {
  6.         if (arguments[0] !== Class) { this.construct.apply(this, arguments); }
  7.     };
  8.     var proto = new this(Class);
  9.     var superClass = this.prototype;
  10.     for (var n in def) {
  11.         var item = def[n];
  12.         if (item instanceof Function) item.father = superClass;
  13.         proto[n] = item;
  14.     }
  15.     subClass.prototype = proto;
  16.     //赋给这个新的子类同样的静态extend方法
  17.     subClass.extend = this.extend;
  18.     return subClass;
  19. };

附录二、寄生组合继承实现多继承,并实现子类调用父类方法案例

  1. // 定义一个房间类
  2. function Room() {
  3.     // 属性
  4.     this.name = name || 'Zoom';
  5. }
  6. // 原型方法
  7. Room.prototype.open = function () {
  8.     console.log("Father." + this.name + '正在开门');
  9. };
  10. // 定义一个动物类
  11. function Animal(name) {
  12.     // 属性
  13.     this.name = name || 'Animal';
  14.     // 实例方法
  15.     this.sleep = function () {
  16.         console.log(this.name + '正在睡觉!');
  17.     }
  18. }
  19. // 原型方法
  20. Animal.prototype.eat = function (food) {
  21.     console.log("Father." + this.name + '正在吃:' + food);
  22. };
  23. function Cat(name) {
  24.     Animal.call(this);
  25.     Room.call(this);
  26.     this.name = name || 'Tom';
  27. }
  28. // Cat类
  29. (function () {
  30.     Cat.prototype.constructor = Cat;
  31.     Cat.prototype.eat = function (food) {
  32.         console.log("SubClass." + this.name + '正在吃:' + food);
  33.         Animal.prototype.eat.apply(this, Array.prototype.slice.apply(arguments));
  34.     };
  35.     Cat.prototype.open = function () {
  36.         console.log("SubClass." + this.name + '正在开门');
  37.         Room.prototype.open.apply(this, Array.prototype.slice.apply(arguments));
  38.     };
  39. })();
  40. // Test Code
  41. var cat = new Cat();
  42. console.log(cat.name);
  43. cat.open();
  44. cat.eat('fish'); //cat正在吃:fish
  45. console.log(cat instanceof Animal); // false
  46. console.log(cat instanceof Cat); //true

测试结果:

附录三、参考文章

https://blog.csdn.net/rainxie_/article/details/39991173

转载于:https://www.cnblogs.com/xyb0226/p/9127424.html

JavaScript中子类调用父类方法的实现相关推荐

  1. c++中子类调用父类方法的方法

    在c++中子类调用父类方法的方法和java所用的方式不一样, java使用super指针就可以调用,c++中虽然也有this指针,但是不能用super去调用父类方法. c++用的方法为:fatherC ...

  2. python中子类调用父类的初始化方法

    http://bestchenwu.iteye.com/blog/1044848 http://www.crazyant.net/1303.html 一直不太理解python的初始化方法,今天找了下资 ...

  3. C#中子类调用父类的实现方法

    本文实例讲述了C#中实现子类调用父类的方法,分享给大家供大家参考之用.具体方法如下: public class Person {public Person(){Console.WriteLine(&q ...

  4. python子类如何调用父类方法_python中子类调用父类函数的方法示例

    前言 本文主要给大家介绍了关于python子类调用父类函数的相关内容,Python中子类中的__init__()函数会覆盖父类的函数,一些情况往往需要在子类里调用父类函数.下面话不多说了,来一起看看详 ...

  5. 关于Java中子类调用父类方法

    当一个类继承于另一个类,子类中没有父类的方法时.用子类的对象调用方法时,会首先在子类中查找,如果子类中没有改方法,再到父类中查找. 当一个方法只在父类中定义时,调用该方法时会使用父类中的属性.  如果 ...

  6. insert时调用本身字段_java中子类调用父类构造方法注意事项

    protected继承 继承有个特点,就是子类无法访问父类的private字段或者private方法.例如,Student类就无法访问Person类的name和age字段: class Person ...

  7. MFC中子类调用父类成员

    需求:首先是不建议在子类中调用父类成员,但有时必须要用可用下面代码. 代码: #include"CSend_ImageDlg.h"//*******//CSend_ImageDlg ...

  8. javascript中子类如何继承父类

    参考阮一峰的文章:http://javascript.ruanyifeng.com/oop/inheritance.html#toc4 function Shape() {this.x = 0;thi ...

  9. php 中如何重载父类的方法_PHP中子类重载父类的方法【parent::方法名】

    在PHP中不能定义重名的函数,也包括不能再同一个类中定义重名的方法,所以也就没有方法重载.单在子类中可以定义和父类重名的方法,因为父类的方法已经在子类中存在,这样在子类中就可以把从父类中继承过来的方法 ...

最新文章

  1. 【11平台天梯】【原理分析】11平台天梯原理分析
  2. Newton差分插值性质证明(均差与差分的关系证明)
  3. nRF52832 中断相关
  4. java 启动程序设置classpath/加载jar、类的方式
  5. Ubuntu 16.04 安装 ROS
  6. CF313D Ilya and Roads(区间DP)
  7. 前端开发还可以这么玩?元数据实践分享
  8. 小微数字风控必学-冷启动开发风险评分(含实操)
  9. NLP--- 将改变你未来沟通方式的7种NLP技术(第二部分)
  10. unity透明通道加颜色_关于Unity伽马校正的一点笔记
  11. 天勤数据结构完全二叉树选择题
  12. y480 linux无线网卡驱动,联想y480无线网卡驱动下载
  13. QT QComboBox使用详解
  14. 【异常】because it is a JDK dynamic proxy that implements
  15. 服务器系统2008R2安全模式,server 2008 r2怎么进入安全模式
  16. 三色球问题python_面试题-三色球问题
  17. Ubuntu系统切换jdk版本
  18. 蓝牙防水耳机排行榜前十名,防水音质表现好的蓝牙耳机推荐
  19. Mac键盘修改F1-F12为功能键,神器karabiner-elements
  20. Android App 可以定时启动! 并且完成短信自动发送获取内容功能 (以获取闪讯密码为例 大学宿舍宽带)

热门文章

  1. python import sql脚本_13-模块介绍-import两种方式-py文件的两种用途-模块搜索路径-项目开发的目录规范...
  2. 收藏 | 图解 Git 工作原理
  3. Keras requires TensorFlow 2.2 or higher怎么办?
  4. CVPR 2020 Oral |目标检测+分割均实现SOTA!厦大提出协同学习网络
  5. Python 按坐标进行文字剪裁
  6. 推荐系统遇上深度学习(六)--PNN模型理论和实践
  7. 针对Hybrid A*论文解析(5)中的方法的一些验证
  8. Hybrid A*论文解析(3)
  9. 6*6行列式相加的c语言,求行列式的值,用C语言怎么写啊?
  10. 对一次通过CISSP考试的建议