js各种继承方式和优缺点的介绍
作者: default

写在前面

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

注意:

跟《JavaScript深入之创建对象》一样,更像是笔记。

哎,再让我感叹一句:《JavaScript高级程序设计》写得真是太好了!

1.原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.引用类型的属性被所有实例共享,举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.借用构造函数(经典继承)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 传参

举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.组合继承

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.原型式继承

1
2
3
4
5
function createObj(o) {
  function F(){}
  F.prototype = o;
  return new F();
}

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

缺点:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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. 寄生式继承

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

1
2
3
4
5
6
7
function createObj (o) {
  var clone = object.create(o);
  clone.sayName = function () {
    console.log('hi');
  }
  return clone;
}

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

6. 寄生组合式继承

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)

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

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

1
Child.prototype = new Parent();

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

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

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

1
Parent.call(this, name);

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

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

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

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

看看如何实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。

js各种继承方式和优缺点的介绍的更多相关文章

  1. js 中继承方式小谈

    题外话 前段时间面试中笔试题有这道题目: 请实现一个继承链,要求如下: 构造函数A():构造函数中有consoleA方法,可以实现console.log("a") 实例对象 a:a ...

  2. js各继承方法的优缺点

    在js中有很多种继承的方法,下面总结这些方法的优缺点. ####1.原型链继承 优点: 非常纯粹的继承关系,实例是子类的实例,也是父类的实例 父类新增原型方法/原型属性,子类都能访问到 简单,易于实现 ...

  3. js的三种继承方式及其优缺点

    [转] 第一种,prototype的方式: //父类 function person(){ this.hair = 'black'; this.eye = 'black'; this.skin = ' ...

  4. javascript中继承方式及优缺点(三)

    文以<JavaScript高级程序设计>上的内容为骨架,补充了ES6 Class的相关内容,从我认为更容易理解的角度将继承这件事叙述出来,希望大家能有所收获. 1. 继承分类 先来个整体印 ...

  5. JavaScript各种继承方式和优缺点

    好久没写博客啦,嘻嘻,这个月是2017年的最后一个月啦,大家应该都开始忙着写年终总结了吧,嘻嘻,小颖今天给大家分享下Javascript中的几种继承方式以及他们的优缺点. 1.借助构造函数实现继承 原 ...

  6. js的继承方式分别适合哪些应用场景?

    一.原型链 利用 Person.prototype = new Animal("Human") 实现继承: static式继承.能继承Animal.prototype.不可多重继承 ...

  7. JS中继承方式总结

    说在前面:为了使代码更为简洁方便理解, 本文中的代码均将"非核心实现"部分的代码移出. 一.原型链方式关于原型链,可点击<深入浅出,JS原型链的工作原理>,本文不再重复 ...

  8. javascript中继承方式及优缺点(一)

    分别介绍原型链继承.call/apply继承(借用构造函数继承).组合继承.原型式继承.寄生式继承.寄生组合式继承 1. 原型链继承 核心:将父类的实例作为子类的原型 function SuperTy ...

  9. javascript中继承方式及优缺点(二)

    一.原型链继承 方式1: 原型链继承 (1)流程: ​ 1.定义父类型构造函数. ​ 2.给父类型的原型添加方法. ​ 3.定义子类型的构造函数. ​ 4.创建父类型的对象赋值给子类型的原型. ​ 5 ...

随机推荐

  1. 【Unity3D】射箭打靶游戏(简单工厂+物理引擎编程)

    打靶游戏:     1.靶对象为 5 环,按环计分:    2.箭对象,射中后要插在靶上:    3.游戏仅一轮,无限 trials: 增强要求:  添加一个风向和强度标志,提高难度 游戏成品图: U ...

  2. Android 调节图片工具类

    package com.base.changeimage; import android.graphics.Bitmap; import android.graphics.Canvas; import ...

  3. 【extjs6学习笔记】1.8 初始: ExtJS命名约定

    Convention for Description Example Class 类名应该在CamelCase中 MyCustomClass 类名应包含字母数字字符. 如果属于技术术语,则允许使用数字 ...

  4. Outlook 2016 自动发送/接收无法正常工作

    如果您的自动/发送接收由于某种原因停止工作,可能会非常令人沮丧,因为您必须记住手动执行发送/接收(F9).如果您遇到Outlook无法自动发送或接收电子邮件的问题,可以尝试以下几项操作. #1 发送/ ...

  5. oracle 11g r2安装

    安装环境:windows 7 安装版本:Oracle_win32_11gR2 目的:用于模拟服务器环境,学习Oracle操作 1. 下载oracle 11g r2,下载地址:www.oracle.co ...

  6. 使用ABAP批量下载有道云笔记中的图片

    Jerry喜欢用有道云笔记这款软件做自己的知识管理和知识体系的构建. 当您看到一篇好的有道云笔记分享时,可能会想将其精美的图片下载到本地.作为程序猿,我们不会去手动一张张下载.写个程序帮我们自动下载吧 ...

  7. C10 C语言数据结构

    目录 枚举 结构体 共用体 枚举 enum enum枚举是 C 语言中的一种基本数据类型,它可以让数据更简洁,更易读. 枚举语法定义格式为: enum 枚举名 {枚举元素1,枚举元素2,……}; 枚举 ...

  8. tcp 高性能服务, netty,mqtt

    1. io 线程不要有比较长的服务. 全部异步化. [1] netty 权威指南上只是说业务复杂时派发到业务线程池种. 共用的线程池最好都轻量. 多层线程池后, 下层的可以进行隔离. 这个是 mqtt ...

  9. java中求几个字符串的最大公共子串 使用了比较器Comparator

    package com.swift; import java.util.ArrayList; import java.util.Collections; import java.util.Compar ...

  10. IOS使用Jenkins进行持续集成

    本文主要讲述在开发过程中,提高工作效率而进行的IOS-Jenkins的持续集成. 背景 平时我们开发完成IOS项目,需要打包给测试人员进行测试.其中的过程需要重复进行:修改配置项--编译---连接设备 ...