博客
关于我
4大继承模式
阅读量:684 次
发布时间: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/

你可能感兴趣的文章
Hadoop学习笔记—Yarn
查看>>
Jenkins - 部署在Tomcat容器里的Jenkins,提示“反向代理设置有误”
查看>>
wxWidgets源码分析(3) - 消息映射表
查看>>
wxWidgets源码分析(5) - 窗口管理
查看>>
wxWidgets源码分析(8) - MVC架构
查看>>
wxWidgets源码分析(9) - wxString
查看>>
[梁山好汉说IT] 梁山好汉和抢劫银行
查看>>
[源码解析] 消息队列 Kombu 之 基本架构
查看>>
[源码分析] 消息队列 Kombu 之 启动过程
查看>>
wx.NET CLI wrapper for wxWidgets
查看>>
Silverlight for linux 和 DLR(Dynamic Language Runtime)
查看>>
ASP.NET MVC Action Filters
查看>>
Powershell中禁止执行脚本解决办法
查看>>
OO_Unit2 多线程电梯总结
查看>>
git clone 出现fatal: unable to access ‘https://github 错误解决方法
查看>>
04_Mysql配置文件(重要参数)
查看>>
python 加密算法及其相关模块的学习(hashlib,RSA,random,string,math)
查看>>
JavaSE总结
查看>>
Python IO编程
查看>>
CSS入门总结
查看>>