前端实现继承的几种方式,举例

56 阅读1分钟

在前端中,实现继承的方式有多种,下面列举了几种常见的方式:

  1. 原型链继承: 使用原型链实现继承是一种简单的方式,通过将子类的原型对象指向父类的实例,使子类能够继承父类的属性和方法。

    javascriptCopy code
    function Parent() {
      this.name = 'Parent';
    }
    
    Parent.prototype.sayHello = function () {
      console.log('Hello');
    }
    
    function Child() {
      this.age = 5;
    }
    
    Child.prototype = new Parent();
    
    const child = new Child();
    console.log(child.name); // 输出:Parent
    child.sayHello(); // 输出:Hello
    
  2. 构造函数继承: 通过在子类的构造函数中调用父类的构造函数来实现继承,可以借助callapply方法将父类的属性和方法绑定到子类实例上。

    javascriptCopy code
    function Parent() {
      this.name = 'Parent';
    }
    
    Parent.prototype.sayHello = function () {
      console.log('Hello');
    }
    
    function Child() {
      Parent.call(this);
      this.age = 5;
    }
    
    const child = new Child();
    console.log(child.name); // 输出:Parent
    child.sayHello(); // 报错:child.sayHello is not a function
    

    注意,使用构造函数继承无法继承父类原型上的方法。

  3. 组合继承(原型链 + 构造函数继承): 组合继承是将原型链继承和构造函数继承结合起来的一种方式。通过调用父类的构造函数绑定属性,同时将子类的原型对象指向父类的实例,实现同时继承父类的属性和方法。

    javascriptCopy code
    function Parent() {
      this.name = 'Parent';
    }
    
    Parent.prototype.sayHello = function () {
      console.log('Hello');
    }
    
    function Child() {
      Parent.call(this);
      this.age = 5;
    }
    
    Child.prototype = new Parent();
    Child.prototype.constructor = Child;
    
    const child = new Child();
    console.log(child.name); // 输出:Parent
    child.sayHello(); // 输出:Hello
    
  4. ES6的类继承: 在ES6中,通过extends关键字可以很方便地实现类的继承。子类可以继承父类的属性和方法,并可以在子类中添加自己的属性和方法。

    javascriptCopy code
    class Parent {
      constructor() {
        this.name = 'Parent';
      }
    
      sayHello() {
        console.log('Hello');
      }
    }
    
    class Child extends Parent {
      constructor() {
        super();
        this.age = 5;
      }
    }
    
    const child = new Child();
    console.log(child.name); // 输出:Parent
    child.sayHello(); // 输出:Hello
    

    使用ES6的类继承可以更清晰地表达类与类之间的继承关系