返回

跳出思维定势,探秘原型链和常见的继承方法

前端

JavaScript中的原型链体系,就像是一颗枝繁叶茂的大树,每个对象都是树上的一片叶子,而原型链就是将这些叶子连接起来的树枝。原型链允许对象从其原型那里继承属性和方法,这在代码复用和维护方面带来了极大的便利。

在JavaScript中,有以下几种常见的继承方法:

  • 原型式继承: 这种继承方法通过创建一个新对象,并将这个新对象的原型指向父对象来实现继承。这种方法很简单,而且在大多数情况下也足够使用。
  • 类式继承: 这种继承方法使用class来创建类,然后使用extends关键字来扩展这个类。这种方法与Java和C++等语言中的继承方法非常相似。
  • 组合式继承: 这种继承方法将原型式继承和类式继承相结合,以实现更加灵活的继承。这种方法通常用于实现多重继承,即一个子类可以从多个父类继承。

每种继承方法都有其自身的优缺点,在实际项目中应根据具体情况选择合适的继承方法。

原型式继承

原型式继承是一种简单而高效的继承方法。这种方法通过创建一个新对象,并将这个新对象的原型指向父对象来实现继承。以下是原型式继承的具体步骤:

  1. 创建一个父对象。
  2. 使用Object.create()方法创建一个新对象,并将这个新对象的原型指向父对象。
  3. 在新对象中添加属性和方法。

以下是原型式继承的示例代码:

// 创建父对象
var Person = function(name) {
  this.name = name;
};

// 为父对象添加属性和方法
Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name);
};

// 使用原型式继承创建一个子对象
var Student = Object.create(Person);

// 为子对象添加属性和方法
Student.prototype.study = function() {
  console.log("I am studying");
};

// 创建一个子对象实例
var student = new Student("John");

// 调用子对象实例的方法
student.greet(); // 输出: Hello, my name is John
student.study(); // 输出: I am studying

在上面的示例中,Person对象是父对象,Student对象是子对象。Student对象通过Object.create()方法继承了Person对象的属性和方法。然后,Student对象又添加了自己的属性和方法。最后,通过new关键字创建了一个Student对象实例,并调用了这个实例的方法。

类式继承

类式继承是另一种常见的继承方法。这种方法使用class关键字来创建类,然后使用extends关键字来扩展这个类。以下是类式继承的具体步骤:

  1. 创建一个父类。
  2. 使用class关键字创建子类,并使用extends关键字指定父类。
  3. 在子类中添加属性和方法。

以下是类式继承的示例代码:

// 创建父类
class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log("Hello, my name is " + this.name);
  }
}

// 创建子类
class Student extends Person {
  constructor(name, major) {
    super(name);
    this.major = major;
  }

  study() {
    console.log("I am studying " + this.major);
  }
}

// 创建子类实例
var student = new Student("John", "Computer Science");

// 调用子类实例的方法
student.greet(); // 输出: Hello, my name is John
student.study(); // 输出: I am studying Computer Science

在上面的示例中,Person类是父类,Student类是子类。Student类通过extends关键字继承了Person类的属性和方法。然后,Student类又添加了自己的属性和方法。最后,通过new关键字创建了一个Student类实例,并调用了这个实例的方法。

组合式继承

组合式继承将原型式继承和类式继承相结合,以实现更加灵活的继承。这种方法通常用于实现多重继承,即一个子类可以从多个父类继承。以下是组合式继承的具体步骤:

  1. 使用原型式继承创建一个父对象。
  2. 使用类式继承创建一个子类,并使用super()方法调用父对象的构造函数。
  3. 在子类中添加属性和方法。

以下是组合式继承的示例代码:

// 创建父对象
var Person = function(name) {
  this.name = name;
};

// 为父对象添加属性和方法
Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name);
};

// 创建子类
class Student extends Person {
  constructor(name, major) {
    super(name);
    this.major = major;
  }

  study() {
    console.log("I am studying " + this.major);
  }
}

// 创建子类实例
var student = new Student("John", "Computer Science");

// 调用子类实例的方法
student.greet(); // 输出: Hello, my name is John
student.study(); // 输出: I am studying Computer Science

在上面的示例中,Person对象是父对象,Student类是子类。Student类通过super()方法调用了Person对象的构造函数,实现了原型式继承。然后,Student类又添加了自己的属性和方法。最后,通过new关键字创建了一个Student类实例,并调用了这个实例的方法。