登录
首页 >  文章 >  前端

JavaScript类继承的实现方式有以下几种:1.原型链继承(PrototypeInheritance)这是JavaScript最传统的继承方式,通过__proto__属性将子类的原型指向父类的实例。functionParent(){this.name='Parent';}Parent.prototype.sayHello=function(){console.log('HellofromPar

时间:2026-01-10 19:54:48 359浏览 收藏

大家好,我们又见面了啊~本文《JavaScript类继承方法有哪些?》的内容中将会涉及到等等。如果你正在学习文章相关知识,欢迎关注我,以后会给大家带来更多文章相关文章,希望我们能一起进步!下面就开始本文的正式内容~

JavaScript类继承通过extends实现,底层基于原型链;子类需在constructor中调用super()初始化父类this,super可传参并支持方法重写、静态方法及内置类继承。

如何实现继承_javascript中类的继承方式有哪些?

JavaScript 中类的继承主要通过 extends 关键字 实现,这是 ES6 引入的语法糖,底层仍基于原型链。它让子类能复用父类的属性和方法,并支持重写、扩展逻辑。

使用 extends 和 super 实现基础继承

子类通过 extends 声明继承父类,构造函数中必须调用 super()(否则报错),以初始化父类的 this。super() 相当于执行父类 constructor。

  • 不调用 super():子类构造函数中无法访问 this,会直接报 ReferenceError
  • super() 必须在使用 this 之前调用
  • super 可以传参,这些参数会传给父类 constructor

示例:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() { console.log(`${this.name} 发声`); }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 初始化父类 this
    this.breed = breed;
  }
  speak() { console.log(`${this.name} 汪汪!`); }
}

方法重写与 super 调用父类方法

子类可定义同名方法覆盖父类逻辑;若需在子类方法中调用父类版本,用 super.方法名()

  • super 不仅可用于 constructor,也可用于普通方法和 getter/setter
  • super 指向父类的原型对象(即 Parent.prototype),不是父类实例
  • 静态方法中 super 指向父类本身(Parent)

例如:speak() { super.speak(); console.log('然后摇尾巴'); }

静态方法与继承关系

static 方法也会被继承。子类可通过 子类名.静态方法 调用父类静态方法,也可用 super.静态方法 在子类静态方法中调用父类版本。

  • class A { static foo() { return 'A'; } }
    class B extends A {}
    B.foo(); // 'A'
  • class C extends A { static foo() { return super.foo() + ' + C'; } }

继承内置类(如 Array、Error)

extends 可继承原生构造函数,使自定义类拥有内置行为(如 instanceof 正确、数组方法可用)。

  • class MyArray extends Array {}
    const arr = new MyArray(1, 2);
    arr.map(x => x * 2); // ✅ 正常工作
  • 注意:某些内置类(如 Promise)在旧环境可能有兼容性限制,但现代引擎普遍支持

基本上就这些。虽然语法简洁,但理解 super 的绑定时机和 this 的初始化顺序很关键——它不是魔法,只是对原型链和 [[Construct]] 的封装。

好了,本文到此结束,带大家了解了《JavaScript类继承的实现方式有以下几种:1.原型链继承(PrototypeInheritance)这是JavaScript最传统的继承方式,通过__proto__属性将子类的原型指向父类的实例。functionParent(){this.name='Parent';}Parent.prototype.sayHello=function(){console.log('HellofromParent');};functionChild(){this.age=20;}Child.prototype=newParent();//原型链继承Child.prototype.constructor=Child;constchild=newChild();child.sayHello();//输出:HellofromParent优点:简单直接。缺点:父类的实例属性会被所有子类共享,容易引起数据污染。2.借用构造函数继承(ConstructorStealing)通过在子类构造函数中调用父类构造函数,来继承父类的属性。functionParent(name){this.name=name;}functionChild(name,age){Parent.call(this,name);//借用构造函数this.age=age;}constchild=newChild('Alice',20);console.log(child.name);//Aliceconsole.log(child.age);//20优点:可以传递参数,避免原型链上的引用类型共享问题》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>