博客
关于我
4大继承模式
阅读量:692 次
发布时间:2019-03-17

本文共 1589 字,大约阅读时间需要 5 分钟。

最基础的继承(子继承父)

在 JavaScript 中,最基础的继承方式是通过原型链实现的子类继承父类。在以下代码中,Son 类通过将其原型链指向 Father 实例的原型链,从而继承了 Father 的属性和方法。

function Father() {    this.height = "180cm";}function Son() {}var father = new Father();var son = new Son();Son.prototype = father; // 使 son 的原型链指向 father 的原型

这样,son 实例的原型链会逐步归属于 father 实例以及 Father 构造函数。具体原型链结构如下:

son.__proto__ → son.prototype = Father.prototype → father.__proto__ → Father.prototype

优点:简单好理解

缺点:继承了父亲所有的属性
缺点:无法仅继承特定的属性或方法


兄弟继承兄弟

这种继承方式的特点是多个子类可以互相继承。例如,Brother1Brother2 mutually 可以继承对方的属性和方法。

function Brother1() {    this.name = name;    this.age = age;}function Brother2() {}var brother1 = new Brother1();var brother2 = new Brother2();Brother1.prototype = Brother2.prototype;

这样,Brother1Brother2 的原型链都会指向 Brother2.prototype

优点:相互继承

缺点:修改任何一个子类的原型会影响另一个子类
缺点:不支持单独继承特定属性或方法


非标准继承(特定场景优化)

这种方式通过 Function.call 将子类的 this 指向父类实例,从而继承父类的属性和方法。这种方式通常在特定场景下使用,以避免使用原型链,直接继承父类属性。

function Father(name, age, sex) {    this.name = name;    this.age = age;    this.sex = sex;}function Son(name, age, sex) {    Father.call(Son, name, age, sex);}

优点:不用设计原型链结构

缺点:需要强制继承父类的所有属性和方法
缺点:不支持添加额外属性或方法


圣杯模式继承(高级继承方式)

圣杯模式通过引入一个中间类(Templator)来实现特定于子类的继承方式。这种方式可以在继承父类属性的同时,避免来自其他子类的干扰。

function Father() {}function Son() {}function Temp() {}// 创建中间商实例var temp = new Temp();// Son inherit from Temp,并记录构造函数Son.prototype = temp;Son.prototype.constructor = Son;// 添加原型链指向FatherSon.prototype.uber = Father.prototype;var son = new Son();// son 的原型链结构:Son.prototype → temp → Father.prototype

优点:仅继承特定的父类属性和方法

缺点:引入了中间商类
缺点:需要手动绑定构造函数

通过以上多种继承方式,可以根据具体需求选择最合适的方案。你认为哪种方式最适合你的项目?

转载地址:http://xtrhz.baihongyu.com/

你可能感兴趣的文章
MultCloud – 支持数据互传的网盘管理
查看>>
MySQL 8.0.23中复制架构从节点自动故障转移
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>