深入理解 JavaScript 继承机制

目录

引言

一、原型链继承

二、借用构造函数继承

三、组合继承

四、ES6 类继承

引言

        在 JavaScript 中,继承是一种强大的特性,它允许我们基于已有的对象(称为父类或基类)创建新的对象(称为子类或派生类)。子类可以继承父类的属性和方法,同时又可以添加新的属性和方法,实现代码的复用和扩展。本文将详细探讨 JavaScript 中的继承机制。

一、原型链继承

        JavaScript 中的每个对象都有一个原型对象(__proto__),而原型对象本身也是一个对象,也有自己的原型对象,这样就形成了一个原型链。当访问一个对象的属性或方法时,如果该对象自身不存在这个属性或方法,那么就会沿着原型链向上查找。

        原型链继承的基本思想是,让子类的原型对象指向父类的一个实例。这样,子类就可以继承父类的属性和方法了。

代码示例:

function Parent() {  
  this.name = 'Parent';  
}  
  
Parent.prototype.sayHello = function() {  
  console.log('Hello from Parent');  
};  
  
function Child() {  
  this.age = 10;  
}  
  
// 继承 Parent  
Child.prototype = new Parent();  
  
// 测试  
var child = new Child();  
console.log(child.name); // Parent  
child.sayHello(); // Hello from Parent

原型链详解请移步另一篇博客-->JavaScript原型链深度剖析

二、借用构造函数继承

        借用构造函数继承的基本思想是,在子类构造函数中调用父类构造函数,用call 或 apply 方法将父类构造函数中的属性和方法复制到子类的实例上。

 代码示例:

function Parent(name) {  
  this.name = name;  
}  
  
Parent.prototype.sayHello = function() {  
  console.log('Hello from Parent');  
};  
  
function Child(name, age) {  
  Parent.call(this, name); // 继承 Parent 的 name 属性  
  this.age = age;  
}  
  
// 测试  
var child = new Child('Child', 10);  
console.log(child.name); // Child  
// 注意:这里无法继承到 Parent 原型上的 sayHello 方法  
// child.sayHello(); // TypeError: child.sayHello is not a function

三、组合继承

        组合继承是原型链继承和借用构造函数继承的组合。它使用原型链实现对父类原型属性和方法的继承,同时通过借用构造函数实现对父类实例属性和方法的继承。这样既能在子类型构造函数中向超类型构造函数传参,又可以让子类型原型继承超类型原型。

代码示例:

function Parent(name) {  
  this.name = name;  
}  
  
Parent.prototype.sayHello = function() {  
  console.log('Hello from Parent');  
};  
  
function Child(name, age) {  
  Parent.call(this, name); // 继承 Parent 的 name 属性  
  this.age = age;  
}  
  
// 继承 Parent 的原型属性和方法  
Child.prototype = Object.create(Parent.prototype);  
Child.prototype.constructor = Child;  
  
// 测试  
var child = new Child('Child', 10);  
console.log(child.name); // Child  
child.sayHello(); // Hello from Parent

四、ES6 类继承

        ES6 引入了 class 关键字,使得 JavaScript 的继承机制更加接近传统的面向对象编程语言。在 ES6 中,我们可以使用 extends 关键字实现类之间的继承。

代码示例:

class Parent {  
  constructor(name) {  
    this.name = name;  
  }  
  
  sayHello() {  
    console.log(`Hello from ${this.name}`);  
  }  
}  
  
class Child extends Parent {  
  constructor(name, age) {  
    super(name); // 调用父类的构造函数  
    this.age = age;  
  }  
  
  sayAge() {  
    console.log(`My age is ${this.age}`);  
  }  
}  
  
// 测试  
const child = new Child('Child', 10);  
child.sayHello(); // Hello from Child  
child.sayAge(); // My age is 10
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值