当前位置: 首页 > news >正文

继承的多种方式和优缺点

写在前面

本文讲解JavaScript各种继承方式和优缺点。

但是注意:

这篇文章更像是笔记,哎,再让我感叹一句:《JavaScript高级程序设计》写得真是太好了!

1.原型链继承

function Parent () {
    this.name = 'kevin'; } Parent.prototype.getName = function () { console.log(this.name); } function Child () { } Child.prototype = new Parent(); var child1 = new Child(); console.log(child1.getName()) // kevin

问题:

1.引用类型的属性被所有实例共享,举个例子:

function Parent () {
    this.names = ['kevin', 'daisy']; } function Child () { } Child.prototype = new Parent(); var child1 = new Child(); child1.names.push('yayu'); console.log(child1.names); // ["kevin", "daisy", "yayu"] var child2 = new Child(); console.log(child2.names); // ["kevin", "daisy", "yayu"]

2.在创建 Child 的实例时,不能向Parent传参

2.借用构造函数(经典继承)

function Parent () {
    this.names = ['kevin', 'daisy']; } function Child () { Parent.call(this); } var child1 = new Child(); child1.names.push('yayu'); console.log(child1.names); // ["kevin", "daisy", "yayu"] var child2 = new Child(); console.log(child2.names); // ["kevin", "daisy"]

优点:

1.避免了引用类型的属性被所有实例共享

2.可以在 Child 中向 Parent 传参

举个例子:

function Parent (name) {
    this.name = name; } function Child (name) { Parent.call(this, name); } var child1 = new Child('kevin'); console.log(child1.name); // kevin var child2 = new Child('daisy'); console.log(child2.name); // daisy

缺点:

方法都在构造函数中定义,每次创建实例都会创建一遍方法。

3.组合继承

原型链继承和经典继承双剑合璧。

function Parent (name) {
    this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); var child1 = new Child('kevin', '18'); child1.colors.push('black'); console.log(child1.name); // kevin console.log(child1.age); // 18 console.log(child1.colors); // ["red", "blue", "green", "black"] var child2 = new Child('daisy', '20'); console.log(child2.name); // daisy console.log(child2.age); // 20 console.log(child2.colors); // ["red", "blue", "green"]

优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。

4.原型式继承

function createObj(o) {
    function F(){}
    F.prototype = o; return new F(); }

就是 ES5 Object.create 的模拟实现,将传入的对象作为创建的对象的原型。

缺点:

包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。

var person = {
    name: 'kevin', friends: ['daisy', 'kelly'] } var person1 = createObj(person); var person2 = createObj(person); person1.name = 'person1'; console.log(person2.name); // kevin person1.firends.push('taylor'); console.log(person2.friends); // ["daisy", "kelly", "taylor"]

注意:修改person1.name的值,person2.name的值并未发生改变,并不是因为person1person2有独立的 name 值,而是因为person1.name = 'person1',给person1添加了 name 值,并非修改了原型上的 name 值。

5. 寄生式继承

创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。

function createObj (o) {
    var clone = object.create(o); clone.sayName = function () { console.log('hi'); } return clone; }

缺点:跟借用构造函数模式一样,每次创建对象都会创建一遍方法。

6. 寄生组合式继承

为了方便大家阅读,在这里重复一下组合继承的代码:

function Parent (name) {
    this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); var child1 = new Child('kevin', '18'); console.log(child1)

组合继承最大的缺点是会调用两次父构造函数。

一次是设置子类型实例的原型的时候:

Child.prototype = new Parent();

一次在创建子类型实例的时候:

var child1 = new Child('kevin', '18');

回想下 new 的模拟实现,其实在这句中,我们会执行:

Parent.call(this, name);

在这里,我们又会调用了一次 Parent 构造函数。

所以,在这个例子中,如果我们打印 child1 对象,我们会发现 Child.prototype 和 child1 都有一个属性为colors,属性值为['red', 'blue', 'green']

那么我们该如何精益求精,避免这一次重复调用呢?

如果我们不使用 Child.prototype = new Parent() ,而是间接的让 Child.prototype 访问到 Parent.prototype 呢?

看看如何实现:

function Parent (name) {
    this.name = name; this.colors = ['red', 'blue', 'green']; } Parent.prototype.getName = function () { console.log(this.name) } function Child (name, age) { Parent.call(this, name); this.age = age; } // 关键的三步 var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); var child1 = new Child('kevin', '18'); console.log(child1);

最后我们封装一下这个继承方法:

function object(o) {
    function F() {}
    F.prototype = o; return new F(); } function prototype(child, parent) { var prototype = object(parent.prototype); prototype.constructor = child; child.prototype = prototype; } // 当我们使用的时候: prototype(Child, Parent);

引用《JavaScript高级程序设计》中对寄生组合式继承的夸赞就是:

这种方式的高效率体现它只调用了一次 Parent 构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。

相关链接

《JavaScript深入之从原型到原型链》

《JavaScript深入之call和apply的模拟实现》

《JavaScript深入之new的模拟实现》

《JavaScript深入之创建对象》

转载于:https://www.cnblogs.com/guaidianqiao/p/7762244.html

相关文章:

  • HDU1412 {A} + {B}
  • usermod命令和用户密码管理
  • socket传输过程
  • 一次反向代理负载均衡的处理过程
  • 魔方NewLife.Cube升级v2.0
  • 小孩子惊吓到 解决方法 收集
  • 跟小静读CLR via C#(10)-参数
  • iOS安全系列之 HTTPS
  • 解决ssh免密码登录仍然提示输入密码问题
  • [改善Java代码]使用Throwable获得栈信息
  • VMM系列之VMM服务器主机和主机组介绍
  • JavaScript内置对象(二)
  • 私有网盘nextcloud 12的使用介绍
  • win10使用Composer-Setup安装Composer以及使用Composer安装Yii2最新版
  • 面试
  • 《Java编程思想》读书笔记-对象导论
  • 【划重点】MySQL技术内幕:InnoDB存储引擎
  • Apache的基本使用
  • avalon2.2的VM生成过程
  • Centos6.8 使用rpm安装mysql5.7
  • cookie和session
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • JAVA多线程机制解析-volatilesynchronized
  • JS变量作用域
  • js继承的实现方法
  • Netty源码解析1-Buffer
  • SQLServer之创建数据库快照
  • vue脚手架vue-cli
  • 分布式事物理论与实践
  • 构造函数(constructor)与原型链(prototype)关系
  • 快速体验 Sentinel 集群限流功能,只需简单几步
  • 前端性能优化——回流与重绘
  • 为什么要用IPython/Jupyter?
  • 因为阿里,他们成了“杭漂”
  • 好程序员大数据教程Hadoop全分布安装(非HA)
  • 蚂蚁金服CTO程立:真正的技术革命才刚刚开始
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • #NOIP 2014#day.2 T1 无限网络发射器选址
  • #每日一题合集#牛客JZ23-JZ33
  • #我与Java虚拟机的故事#连载19:等我技术变强了,我会去看你的 ​
  • $redis-setphp_redis Set命令,php操作Redis Set函数介绍
  • (2020)Java后端开发----(面试题和笔试题)
  • (floyd+补集) poj 3275
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (附源码)ssm高校实验室 毕业设计 800008
  • (三)centos7案例实战—vmware虚拟机硬盘挂载与卸载
  • (十八)用JAVA编写MP3解码器——迷你播放器
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (四)鸿鹄云架构一服务注册中心
  • (转)Groupon前传:从10个月的失败作品修改,1个月找到成功
  • (转)scrum常见工具列表
  • (转)Unity3DUnity3D在android下调试
  • .describe() python_Python-Win32com-Excel
  • .NET 8 编写 LiteDB vs SQLite 数据库 CRUD 接口性能测试(准备篇)