返回

零基础让你轻松学会在JavaScript中实现继承

前端





## 揭开继承的面纱

### 为什么要继承?
在回答这个问题之前,我们首先要知道继承是什么。在 JavaScript 中,继承是一种将父类对象的属性和方法传递给子类对象的过程,这可以帮助我们复用代码,减少重复,提高开发效率。

### 继承的实现
在 JavaScript 中,实现继承有三种主要方法:
- 复用父构造函数中的代码
- 复用父类的方法
- 基于原型的继承

#### 复用父构造函数中的代码
```javascript
function Parent(name) {
  this.name = name;
}

Parent.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

function Child(name) {
  // 调用父构造函数
  Parent.call(this, name);
}

// 继承父类的方法
Child.prototype = Object.create(Parent.prototype);

// 重写父类的方法
Child.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I am a child.`);
};

const child = new Child('John');
child.greet(); // 输出:Hello, my name is John and I am a child.

在这个例子中,Child 类继承了 Parent 类的属性和方法。当我们创建一个 Child 类的实例时,Parent 类 的构造函数被调用,从而设置了 name 属性。然后,Child 类的方法被添加到实例中,重写了 Parent 类的方法。

复用父类的方法

function Parent() {}

Parent.prototype.greet = function() {
  console.log('Hello, I am the parent.');
};

function Child() {}

// 直接继承父类的方法
Child.prototype = new Parent();

const child = new Child();
child.greet(); // 输出:Hello, I am the parent.

在这个例子中,Child 类继承了 Parent 类的所有方法,包括 greet 方法。当我们创建一个 Child 类的实例时,Parent 类的方法被添加到实例中。

基于原型的继承

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

Parent.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

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

// 将父类的原型对象设置为子类的原型对象
Child.prototype = Parent.prototype;

const child = new Child();
child.greet(); // 输出:Hello, my name is Child.

在这个例子中,Child 类继承了 Parent 类的原型对象,从而继承了 Parent 类的所有属性和方法。当我们创建一个 Child 类的实例时,Parent 类的原型对象被复制到实例中,从而使实例具有 Parent 类的所有属性和方法。

结束语

通过上面的讲解,相信你现在对继承已经有了比较全面的了解。希望这些技巧对你有帮助,也希望你能将这些技巧应用到自己的 JavaScript 项目中,以提高代码的复用性。