Javascript实现继承的几种方式-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

在 JavaScript 中实现继承有多种方式。以下是其中几种常见的方式

1原型链继承
原型链继承是通过将一个对象的实例作为另一个对象的原型来实现继承关系。子对象通过原型链可以访问父对象的属性和方法。

示例

function Parent() {
  this.name = "Parent";
}

Parent.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.name);
};

function Child() {
  this.name = "Child";
}

Child.prototype = new Parent();

const child = new Child();
child.sayHello(); // 输出: Hello, I'm Child

2构造函数继承
构造函数继承是通过在子对象的构造函数中调用父对象的构造函数来实现继承。这种方式可以实现属性的继承但无法继承父对象原型上的方法。

示例

function Parent() {
  this.name = "Parent";
}

function Child() {
  Parent.call(this);
  this.name = "Child";
}

const child = new Child();
console.log(child.name); // 输出: Child

3组合继承
组合继承是将原型链继承和构造函数继承结合起来的一种方式。通过调用父对象的构造函数实现属性的继承并将子对象的原型设置为父对象的实例实现方法的继承。

示例

function Parent() {
  this.name = "Parent";
}

Parent.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.name);
};

function Child() {
  Parent.call(this);
  this.name = "Child";
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child();
child.sayHello(); // 输出: Hello, I'm Child

4ES6 的类继承
在 ES6 中引入了类的概念可以使用 extends 关键字来实现类的继承。子类通过 super 关键字调用父类的构造函数和方法。

示例

class Parent {
  constructor() {
    this.name = "Parent";
  }

  sayHello() {
    console.log("Hello, I'm " + this.name);
  }
}

class Child extends Parent {
  constructor() {
    super();
    this.name = "Child";
  }
}

const child = new Child();
child.sayHello(); // 输出: Hello, I'm Child
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: JavaScriptJava