JavaScript中子类调用父类方法的实现
一、前言
最近在项目中,前端框架使用JavaScript面向对象编程,遇到了诸多问题,其中最典型的问题就是子类调用父类(super class)同名方法,也就是如C#中子类中调用父类函数base.**。以下摘录了园友幻天芒对JavaScript实现继承的几种方式 的具体介绍以作备忘。
二、JavaScript实现继承的几种方式
既然要实现继承,那么我们首先得有一个基类,代码如下:
- // 定义一个动物类
- function Animal(name) {
- // 属性
- this.name = name || 'Animal';
- // 实例方法
- this.sleep = function () {
- console.log(this.name + '正在睡觉!');
- }
- }
- // 原型方法
- Animal.prototype.eat = function (food) {
- console.log(this.name + '正在吃:' + food);
- };
1、原型链继承
核心: 将父类的实例作为子类的原型
- //定义动物猫
- function Cat() {
- }
- Cat.prototype = new Animal();
- Cat.prototype.name = 'cat';
- // Test Code
- var cat = new Cat();
- console.log(cat.name); //cat
- cat.eat('fish'); //cat正在吃:fish
- cat.sleep(); //cat正在睡觉
- console.log(cat instanceof Animal); //true
- console.log(cat instanceof Cat); //true
特点:
1.非常纯粹的继承关系,实例是子类的实例,也是父类的实例;
2.父类新增原型方法/原型属性,子类都能访问到;
3.简单,易于实现;
缺点:
1.要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
2.无法实现多继承;
3.创建子类时,无法向父类构造函数传参;
4.来自原型对象的属性是所有实例所共享;
2、构造继承
核心:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)
- function Cat(name) {
- Animal.call(this);
- this.name = name || 'Tom';
- }
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // false
- console.log(cat instanceof Cat); // true
特点:
1. 解决了1中,子类实例共享父类引用属性的问题;
2. 创建子类实例时,可以向父类传递参数;
3. 可以实现多继承(call多个父类对象);
缺点:
1. 实例并不是父类的实例,只是子类的实例;
2. 只能继承父类的实例属性和方法,不能继承原型属性/方法;
3. 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能;
3、实例继承
核心:为父类实例添加新特性,作为子类实例返回
- function Cat(name) {
- var instance = new Animal();
- instance.name = name || 'Tom';
- return instance;
- }
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // true
- console.log(cat instanceof Cat); // false
特点:
1. 不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果;
缺点:
2.无法实现多继承;
4、拷贝继承
- function Cat(name) {
- var animal = new Animal();
- for (var p in animal) {
- Cat.prototype[p] = animal[p];
- }
- Cat.prototype.name = name || 'Tom';
- }
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // false
- console.log(cat instanceof Cat); // true
特点:
1. 支持多继承;
缺点:
1. 效率较低,内存占用高(因为要拷贝父类的属性);
2. 无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到);
5、组合继承
核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
- function Cat(name) {
- Animal.call(this);
- this.name = name || 'Tom';
- }
- Cat.prototype = new Animal();
- Cat.prototype.constructor = Cat;
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // true
- console.log(cat instanceof Cat); // true
特点:
1.弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法;
2.既是子类的实例,也是父类的实例;
3.不存在引用属性共享问题;
4.可传参;
5.函数可复用;
缺点:
1. 调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了);
6、寄生组合继承
核心:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点
- function Cat(name){
- Animal.call(this);
- this.name = name || 'Tom';
- }
- (function(){
- // 创建一个没有实例方法的类
- var Super = function(){};
- Super.prototype = Animal.prototype;
- //将实例作为子类的原型
- Cat.prototype = new Super();
- Cat.prototype.constructor = Cat; // 需要修复下构造函数
- })();
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // true
- console.log(cat instanceof Cat); //true
特点:
1. 堪称完美;
缺点:
1.实现较为复杂;
三、实现子类调用父类方法的解决方案
上述的几种继承方式,如要实现子类Cat,在eat方法中调用父类Animal的eat方法,该如何实现呢? 以寄生组合继承为例:
- // 定义一个动物类
- function Animal(name) {
- // 属性
- this.name = name || 'Animal';
- // 实例方法
- this.sleep = function () {
- console.log(this.name + '正在睡觉!');
- }
- }
- // 原型方法
- Animal.prototype.eat = function (food) {
- console.log("Father." + this.name + '正在吃:' + food);
- };
- function Cat(name) {
- Animal.call(this);
- this.name = name || 'Tom';
- }
- (function () {
- // 创建一个没有实例方法的类
- var Super = function () { };
- Super.prototype = Animal.prototype;
- //将实例作为子类的原型
- Cat.prototype = new Super();
- Cat.prototype.constructor = Cat; // 需要修复下构造函数
- Cat.prototype.eat = function (food) {
- console.log("SubClass." + this.name + '正在吃:' + food);
- Super.prototype.eat.apply(this, Array.prototype.slice.apply(arguments));
- };
- })();
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- cat.eat('fish'); //cat正在吃:fish
- console.log(cat instanceof Animal); // true
- console.log(cat instanceof Cat); //true
测试结果:
其中的关键代码在于:
我们看到,子类要想调用父类的方法,必须使用父类原型方法的apply(Super.prototype.eat.apply), 也就是必须得在子类中使用父类对象,这种以硬编码方式的调用,虽然能解决问题,但确不是特别优雅。
四、优化后的子类调用父类方法的实现方式
以上的继承方式,都不能实现子类调用父类方法, 在重写子类原型函数后,会将继承父类函数给覆盖。先来看实例:
父类:
- var Animal = Class.extend({
- construct: function (name) {
- arguments.callee.father.construct.call(this);
- this.name = name || "Animal";
- },
- eat: function (food) {
- console.log("Father." + this.name + '正在吃:' + food);
- },
- sleep: function () {
- console.log("Father." + this.name + '正在睡觉!');
- }
- });
子类:
- var Cat = Animal.extend({
- construct: function () {
- arguments.callee.father.construct.call(this,"Cat");
- },
- eat: function (food) {
- console.log("SubClass." + this.name + '正在吃:' + food);
- arguments.callee.father.eat.call(this, food);
- },
- sleep: function () {
- console.log("SubClass." + this.name + '正在睡觉!');
- arguments.callee.father.sleep.call(this);
- }
- });
测试代码:
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- console.log(cat.eat('fish'));
- console.log(cat.sleep());
- console.log(cat instanceof Animal); // true
- 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基类
- //定义最顶级类,用于js继承基类
- function Class() { }
- Class.prototype.construct = function () { };
- Class.extend = function (def) {
- var subClass = function () {
- if (arguments[0] !== Class) { this.construct.apply(this, arguments); }
- };
- var proto = new this(Class);
- var superClass = this.prototype;
- for (var n in def) {
- var item = def[n];
- if (item instanceof Function) item.father = superClass;
- proto[n] = item;
- }
- subClass.prototype = proto;
- //赋给这个新的子类同样的静态extend方法
- subClass.extend = this.extend;
- return subClass;
- };
附录二、寄生组合继承实现多继承,并实现子类调用父类方法案例
- // 定义一个房间类
- function Room() {
- // 属性
- this.name = name || 'Zoom';
- }
- // 原型方法
- Room.prototype.open = function () {
- console.log("Father." + this.name + '正在开门');
- };
- // 定义一个动物类
- function Animal(name) {
- // 属性
- this.name = name || 'Animal';
- // 实例方法
- this.sleep = function () {
- console.log(this.name + '正在睡觉!');
- }
- }
- // 原型方法
- Animal.prototype.eat = function (food) {
- console.log("Father." + this.name + '正在吃:' + food);
- };
- function Cat(name) {
- Animal.call(this);
- Room.call(this);
- this.name = name || 'Tom';
- }
- // Cat类
- (function () {
- Cat.prototype.constructor = Cat;
- Cat.prototype.eat = function (food) {
- console.log("SubClass." + this.name + '正在吃:' + food);
- Animal.prototype.eat.apply(this, Array.prototype.slice.apply(arguments));
- };
- Cat.prototype.open = function () {
- console.log("SubClass." + this.name + '正在开门');
- Room.prototype.open.apply(this, Array.prototype.slice.apply(arguments));
- };
- })();
- // Test Code
- var cat = new Cat();
- console.log(cat.name);
- cat.open();
- cat.eat('fish'); //cat正在吃:fish
- console.log(cat instanceof Animal); // false
- console.log(cat instanceof Cat); //true
测试结果:
附录三、参考文章
https://blog.csdn.net/rainxie_/article/details/39991173
转载于:https://www.cnblogs.com/xyb0226/p/9127424.html
JavaScript中子类调用父类方法的实现相关推荐
- c++中子类调用父类方法的方法
在c++中子类调用父类方法的方法和java所用的方式不一样, java使用super指针就可以调用,c++中虽然也有this指针,但是不能用super去调用父类方法. c++用的方法为:fatherC ...
- python中子类调用父类的初始化方法
http://bestchenwu.iteye.com/blog/1044848 http://www.crazyant.net/1303.html 一直不太理解python的初始化方法,今天找了下资 ...
- C#中子类调用父类的实现方法
本文实例讲述了C#中实现子类调用父类的方法,分享给大家供大家参考之用.具体方法如下: public class Person {public Person(){Console.WriteLine(&q ...
- python子类如何调用父类方法_python中子类调用父类函数的方法示例
前言 本文主要给大家介绍了关于python子类调用父类函数的相关内容,Python中子类中的__init__()函数会覆盖父类的函数,一些情况往往需要在子类里调用父类函数.下面话不多说了,来一起看看详 ...
- 关于Java中子类调用父类方法
当一个类继承于另一个类,子类中没有父类的方法时.用子类的对象调用方法时,会首先在子类中查找,如果子类中没有改方法,再到父类中查找. 当一个方法只在父类中定义时,调用该方法时会使用父类中的属性. 如果 ...
- insert时调用本身字段_java中子类调用父类构造方法注意事项
protected继承 继承有个特点,就是子类无法访问父类的private字段或者private方法.例如,Student类就无法访问Person类的name和age字段: class Person ...
- MFC中子类调用父类成员
需求:首先是不建议在子类中调用父类成员,但有时必须要用可用下面代码. 代码: #include"CSend_ImageDlg.h"//*******//CSend_ImageDlg ...
- javascript中子类如何继承父类
参考阮一峰的文章:http://javascript.ruanyifeng.com/oop/inheritance.html#toc4 function Shape() {this.x = 0;thi ...
- php 中如何重载父类的方法_PHP中子类重载父类的方法【parent::方法名】
在PHP中不能定义重名的函数,也包括不能再同一个类中定义重名的方法,所以也就没有方法重载.单在子类中可以定义和父类重名的方法,因为父类的方法已经在子类中存在,这样在子类中就可以把从父类中继承过来的方法 ...
最新文章
- 【11平台天梯】【原理分析】11平台天梯原理分析
- Newton差分插值性质证明(均差与差分的关系证明)
- nRF52832 中断相关
- java 启动程序设置classpath/加载jar、类的方式
- Ubuntu 16.04 安装 ROS
- CF313D Ilya and Roads(区间DP)
- 前端开发还可以这么玩?元数据实践分享
- 小微数字风控必学-冷启动开发风险评分(含实操)
- NLP--- 将改变你未来沟通方式的7种NLP技术(第二部分)
- unity透明通道加颜色_关于Unity伽马校正的一点笔记
- 天勤数据结构完全二叉树选择题
- y480 linux无线网卡驱动,联想y480无线网卡驱动下载
- QT QComboBox使用详解
- 【异常】because it is a JDK dynamic proxy that implements
- 服务器系统2008R2安全模式,server 2008 r2怎么进入安全模式
- 三色球问题python_面试题-三色球问题
- Ubuntu系统切换jdk版本
- 蓝牙防水耳机排行榜前十名,防水音质表现好的蓝牙耳机推荐
- Mac键盘修改F1-F12为功能键,神器karabiner-elements
- Android App 可以定时启动! 并且完成短信自动发送获取内容功能 (以获取闪讯密码为例 大学宿舍宽带)
热门文章
- python import sql脚本_13-模块介绍-import两种方式-py文件的两种用途-模块搜索路径-项目开发的目录规范...
- 收藏 | 图解 Git 工作原理
- Keras requires TensorFlow 2.2 or higher怎么办?
- CVPR 2020 Oral |目标检测+分割均实现SOTA!厦大提出协同学习网络
- Python 按坐标进行文字剪裁
- 推荐系统遇上深度学习(六)--PNN模型理论和实践
- 针对Hybrid A*论文解析(5)中的方法的一些验证
- Hybrid A*论文解析(3)
- 6*6行列式相加的c语言,求行列式的值,用C语言怎么写啊?
- 对一次通过CISSP考试的建议