• js实现继承的三种方式


    前言

    继承是面向对象编程中讨论最多的话题。很多面向对象语言都支持两种继承:接口继承和实现继承。前者只继承方法签名,后者继承实际的方法。接口继承在 ECMAScript 中是不可能的,因为函数没有签名。实现继承是ECMAScript 唯一支持的继承方式,而这主要是通过原型链实现的。

    一、原型链继承

    ECMAScript 把原型链定义为 ECMAScript 的主要继承方式。其基本思想就是通过原型继承多个引用类型的属性和方法。

    我们知道构造函数、原型和实例的存在以下关系:每个构造函数都有一个原型对象,原型有一个属性constructor指回构造函数,而实例有一个内部指针__proto__指向原型。它们的关系如下图所示:
    ​​在这里插入图片描述
    如果原型是另一个类型的实例呢?那就意味着这个原型本身有一个内部指针指向另一个原型,相应地另一个原型也有一个指针指向另一个构造函数。这样就在实例和原型之间构造了一条原型链。这就是原型链的基本构想。

    我们可以通过一个例子来理解一下原型链:

    // 创建Animal
    function Animal() {
      this.name = 'animal';
    }
    Animal.prototype.getAnimalName = function () {
      console.log(this.name + ' getAnimalName');
    }
    // 创建Dog
    function Dog() {
      this.name = 'dog';
    }
    
    //让Dog的原型对象成为了Animal的实例对象,此时Dog就继承自Animal
    Dog.prototype = new Animal();
    //在Dog原型上定义一个方法
    //注意:在使用原型链继承的时候,要在继承之后再去原型对象上定义自己所需的属性和方法
    Dog.prototype.getDogName = function (){
      console.log(this.name + ' getDogName');
    }
    var d1 = new Dog(); //创建Dog的实例对象
    d1.getAnimalName() //dog getAnimalName
    d1.getDogName() //dog getDogName
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    上述例子中,我们定义了两个类型的构造函数:Animal 和 Dog,这两个构造函数又分别定义了一个属性和一个方法。

    代码 Dog.prototype = new Animal(); 通过创建 Animal 的实例并将其赋值给Dog的原型对象,所以Dog. prototype 实现了对 Animal 的继承。这个赋值重写了 Dog 最初的原型,将其替换为Animal 的实例。这意味着 Animal 实例可以访问的所有属性和方法也会存在于 Dog. prototype。这样实现继承之后,我们紧接着又给Dog.prototype,也就是这个 Animal 的实例添加了一个新方法getDogName,最后又创建了 Dog 的实例并调用了它继承的 getAnimalName方法。

    下图展示了 Dog 的实例与两个构造函数及其对应的原型之间的关系:
    在这里插入图片描述
    在读取实例上的属性时,首先会在实例上搜索这个属性。如果没找到,则会继承搜索实例的原型,这就是原型搜索机制。在通过原型链实现继承之后,搜索就可以继承向上,搜索原型的原型。

    △ 分析一下上述例子中最后两行代码的输出:

    • 当Dog的实例对象d1调用getAnimalName()方法时,它会通过三步搜索找到该方法: d1 --> Dog.prototype --> Animal.prototype
    • 当Dog的实例对象d1调用getDogName()方法时,它会通过两步搜索找到该方法:
      d1 --> Dog.prototype
    • 由于d1实例对象上存在name属性,因此不会再去原型上找,所以输出name的值为 ‘dog’

    注意:由于 Dog.prototype 的 constructor 属性被重写为指向Animal,所以 d1.constructor 也指向 Animal,想要指回Dog可以修改Dog.prototype.constructor:

    // 创建Animal
    function Animal() {
      this.name = 'animal';
    }
    Animal.prototype.getAnimalName = function () {
      console.log(this.name + ' getAnimalName');
    }
    // 创建Dog
    function Dog() {
      this.name = 'dog';
    }
    
    //让Dog的原型对象变成了Animal的实例对象
    Dog.prototype = new Animal();
    Dog.prototype.getDogName = function (){
      console.log(this.name + ' getDogName');
    }
    
    console.log(Dog.prototype.constructor); //[Function: Animal]
    // 将Dog.prototype指回自己的构造函数Dog
    Object.defineProperty(Dog.prototype, 'constructor',{
      enumerable: false,
      value: Dog
    })
    console.log(Dog.prototype.constructor); //[Function: Dog]
    
    var d1 = new Dog();
    d1.getAnimalName() //dog getAnimalName
    d1.getDogName() //dog getDogName
    
    • 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

    默认原型

    实际上,原型链中还有一环。默认情况下,所有引用类型都继承自 Object,这也是通过原型链实现的。任何函数的默认原型都是一个 Object 的实例,这意味着这个实例有一个内部指针__proto__指向Object.prototype。这也是为什么自定义类型能够继承包括 toString()、valueOf()在内的所有默认方法的原因。因此前面的例子还有额外一层继承关系,如下图所示:
    在这里插入图片描述
    Dog 继承 Animal,而 Animal 继承 Object。在调用 d1.toString()时,实际上调用的是保存在Object.prototype 上的方法。

    原型与实例的关系

    原型与实例的关系可以通过两种方式来确定:第一种方式是使用 instanceof 操作符,如果一个实例的原型链中出现过相应的构造函数,则 instanceof 返回 true。如下例所示:

    //instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。
    //Object.prototype出现在d1的原型链上,返回true
    console.log(d1 instanceof Object);  //true
    console.log(d1 instanceof Animal);  //true
    console.log(d1 instanceof Dog);     //true
    
    • 1
    • 2
    • 3
    • 4
    • 5

    第二种方式是使用 isPrototypeOf()方法。原型链中的每个原型都可以调用这个方法,如下例所示,只要原型链中包含这个原型,这个方法就返回 true:

    //Object.prototype在d1的原型链上,返回true
    console.log(Object.prototype.isPrototypeOf(d1)); // true 
    console.log(Animal.prototype.isPrototypeOf(d1)); // true 
    console.log(Dog.prototype.isPrototypeOf(d1)); // true
    
    • 1
    • 2
    • 3
    • 4

    关于方法

    子构造函数有时候需要覆盖父构造函数的方法,或者增加父构造函数没有的方法。为此,这些方法必须在原型赋值之后再添加到原型上。来看下面的例子:

    // 创建Animal
    function Animal() {
      this.name = 'animal';
    }
    Animal.prototype.getAnimalName = function () {
      console.log(this.name + ' getAnimalName');
    }
    // 创建Dog
    function Dog() {
      this.name = 'dog';
    }
    
    //让Dog的原型对象变成了Animal的实例对象
    Dog.prototype = new Animal();
    // 将Dog.prototype指回自己的构造函数Dog
    Object.defineProperty(Dog.prototype, 'constructor',{
      enumerable: false,
      value: Dog
    })
    
    //新方法
    Dog.prototype.getDogName = function (){
      console.log(this.name + ' getDogName');
    }
    //覆盖父构造函数Animal的方法
    Dog.prototype.getAnimalName = function (){
      console.log('我覆盖了父构造函数的方法');
    }
    
    var d1 = new Dog();
    d1.getAnimalName() //我覆盖了父构造函数的方法
    d1.getDogName() //dog getDogName
    
    var a1 = new Animal()
    a1.getAnimalName() //animal getAnimalName
    
    • 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
    • 33
    • 34
    • 35

    当实例对象调用属性和方法时,会现在实例对象自身身上找,找不到就往原型链一层一层地往上找,直到找到为止。下图就是一个简单的原型链,展示了上述例子中实例对象在原型链上搜索方法的过程:
    在这里插入图片描述

    原型链的破坏

    以对象字面量方式创建原型方法会破坏之前的原型链,因为这相当于重写了原型链。

    // 创建Animal
    function Animal() {
      this.name = 'animal';
    }
    Animal.prototype.getAnimalName = function () {
      console.log(this.name + ' getAnimalName');
    }
    // 创建Dog
    function Dog() {
      this.name = 'dog';
    }
    
    //让Dog的原型对象变成了Animal的实例对象
    Dog.prototype = new Animal();
    // 将Dog.prototype指回自己的构造函数Dog
    Object.defineProperty(Dog.prototype, 'constructor',{
      enumerable: false,
      value: Dog
    })
    
    Dog.prototype = {
      getDogName() {
        console.log(this.name);
      },
      someOtherMethod() {
        return false;
      }
    };
    
    var d1 = new Dog();
    d1.getAnimalName() //报错 TypeError: d1.getAnimalName is not a function
    
    • 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

    在这段代码中,子类的原型在被赋值为 Animal 的实例后,又被一个对象字面量覆盖了,覆盖后的原型是一个 Object 的实例,而不再是 Animal 的实例。因此之前的原型链就断了,Dog和 Animal 之间也没有关系了。

    原型链的问题

    原型链虽然是实现继承的强大工具,但它也有问题。主要问题出现在原型中包含引用值的时候,原型中包含的引用值会在所有实例间共享,这也是为什么属性通常会在构造函数中定义而不会定义在原型上的原因。在使用原型实现继承时,原型实际上变成了另一个类型的实例。这意味着原先的实例属性摇身一变成为了原型属性。

    function Animal() {
      this.categorys = ["cat", "rabbit"];
    }
    function Dog() { }
    // 继承 Animal 
    Dog.prototype = new Animal();
    var d1 = new Dog();
    d1.categorys.push("dog");
    console.log(d1.categorys); // [ 'cat', 'rabbit', 'dog' ]
    var d2 = new Dog();
    console.log(d2.categorys); // [ 'cat', 'rabbit', 'dog' ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这个例子中,Animal 构造函数定义了一个 categorys 属性,其中包含一个数组(引用值)。每个Animal 的实例都会有自己的 categorys 属性,包含自己的数组。但是,当 Dog 通过原型继承Animal 后,Dog.prototype 变成了 Animal 的一个实例,因而也获得了自己的 categorys属性。这类似于创建了Dog.prototype.categorys 属性。最终结果是,Dog 的所有实例都会共享这个 categorys 属性。这一点通过d1.categorys 上的修改也能反映到 d2.categorys上就可以看出来。

    原型链的第二个问题是,子构造函数在实例化时不能给父构造函数传参。事实上,我们无法在不影响所有对象实例的情况下把参数传进父类的构造函数。再加上之前提到的原型中包含引用值的问题,就导致原型链基本不会被单独使用。

    二、经典继承

    为了解决原型包含引用值导致的继承问题,一种叫作“盗用构造函数”(constructor stealing)的技术在开发社区流行起来(这种技术有时也称作“对象伪装”或“经典继承”)。

    基本思路很简单:在子构造函数中调用父构造函数。因为毕竟函数就是在特定上下文中执行代码的简单对象,所以可以使用apply()call()方法以新创建的对象为上下文执行构造函数。

    function Animal() {
      this.categorys = ["cat", "rabbit"];
    }
    function Dog() {
      // 继承 Animal 
      Animal.call(this);
    }
    
    var d1 = new Dog();
    d1.categorys.push("dog");
    console.log(d1.categorys); // [ 'cat', 'rabbit', 'dog' ]
    var d2 = new Dog();
    console.log(d2.categorys); // [ 'cat', 'rabbit' ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    var d1 = new Dog() d1调用Dog构造函数,所以其内部this的值指向的是d1,所以Animal.call(this)就相当于Animal.call(d1),就相当于d1.Animal()。最后,d1去调用Animal方法时,Animal内部的this指向就指向了d1。那么Animal内部this上的所有属性和方法,都被拷贝到了d1上。所以,每个实例都具有自己的categorys属性副本。他们互不影响。

    传递参数

    相比于使用原型链,经典继承函数的一个优点就是可以在子类构造函数中向父类构造函数传参。

    function Animal(name) {
      this.name = name;
    }
    function Dog() {
      // 继承 Animal 并传参
      Animal.call(this, "zhangsan");
      // 实例属性
      this.age = 29;
    }
    var d = new Dog();
    console.log(d.name); // zhangsan
    console.log(d.age); // 29
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这个例子中,Animal 构造函数接收一个参数 name,然后将它赋值给一个属性。在 Dog构造函数中调用 Animal 构造函数时传入这个参数,实际上会在 Dog 的实例上定义 name 属性。为确保 Animal 构造函数不会覆盖 Dog 定义的属性,可以在调用父构造函数之后再给子实例添加额外的属性。

    经典继承函数的问题

    经典继承函数的主要缺点是使用构造函数模式自定义类型的问题:必须在构造函数中定义方法,因此函数不能重用。此外,子类也不能访问父类原型上定义的方法,因此所有类型只能使用构造函数模式。由于存在这些问题,经典继承函数基本上也不能单独使用。

    总结:
    1、创建的实例并不是父类的实例,只是子类的实例。

    2、没有拼接原型链,不能使用 instanceof。因为子类的实例只继承了父构造函数的实例属性/方法,没有继承父构造函数的原型对象中的属性/方法。

    3、每个子构造函数的实例都持有父构造函数的实例方法的副本,浪费内存,影响性能,而且无法实现父类的实例方法的复用。

    三、组合继承

    组合继承(有时候也叫伪经典继承综合了原型链和经典继承函数,将两者的优点集中了起来。

    基本的思路是 使用原型链继承原型上的属性和方法,而通过经典继承函数继承实例属性。这样既可以把方法定义在原型上以实现重用,又可以让每个实例都有自己的属性。

    function Animal(name) {
      this.name = name;
      this.categorys = ["cat", "rabbit"];
    }
    Animal.prototype.sayName = function () {
      console.log(this.name);
    };
    function Dog(name, age) {
      // 继承属性
      Animal.call(this, name);
      this.age = age;
    }
    // 继承方法
    Dog.prototype = new Animal();
    Dog.prototype.sayAge = function () {
      console.log(this.age);
    };
    var d1 = new Dog("zhangsan", 29);
    d1.categorys.push("dog");
    console.log(d1.categorys); // [ 'cat', 'rabbit', 'dog' ]
    d1.sayName(); // zhangsan
    d1.sayAge(); // 29 
    
    var d2 = new Dog("lisi", 27);
    console.log(d2.categorys); // [ 'cat', 'rabbit' ]
    d2.sayName(); // lisi
    d2.sayAge(); // 27
    
    • 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

    在这个例子中,Animal 构造函数定义了两个属性,name 和 categorys,而它的原型上也定义了一个方法叫 sayName()。Dog 构造函数调用了 Animal 构造函数,传入了 name 参数,然后又定义了自己的属性 age。此外,Dog.prototype 也被赋值为 Animal 的实例。原型赋值之后,又在这个原型上添加了新方法 sayAge()。这样,就可以创建两个 Dog 实例,让这两个实例都有自己的属性,包括 categorys,同时还共享相同的方法。

    组合继承弥补了原型链和经典继承函数的不足,是 JavaScript 中使用最多的继承模式。而且组合继承也保留了 instanceof 操作符和 isPrototypeOf()方法识别合成对象的能力。

  • 相关阅读:
    微服务技术
    linux0.11-虚拟内存
    Java(七)——集合框架---ArrayList集合、LinkedList集合
    11. Junit
    虚拟机开启网络代理设置
    软考考完了,如何评职称?
    如何设置代理ip服务器地址
    MySQL 高级(进阶) SQL 语句 (一)
    中小微企业如何快速开发信息化系统
    如何参与开源项目 - 细说 GitHub 上的 PR 全过程
  • 原文地址:https://blog.csdn.net/lq313131/article/details/126432548