JavaScript中如何实现继承_ES5和ES6继承方式对比

admin 百科 11
ES5继承靠构造函数借用和原型链组合实现,ES6用class/extends/super语法糖并自动建立完整原型链与静态继承。

JavaScript中如何实现继承_ES5和ES6继承方式对比-第1张图片-佛山资讯网

ES5继承:靠构造函数和原型链配合

ES5没有class关键字,实现继承主要靠组合使用构造函数借用(call/apply)和原型链继承。核心思路是:子类实例先拥有父类的实例属性,再让子类原型指向父类原型的副本,从而共享方法。

常见写法(寄生组合式继承,最推荐):

function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {
  console.log('Hello from ' + this.name);
};

function Child(name, age) {
  Parent.call(this, name); // 借用构造函数,继承实例属性
  this.age = age;
}

// 关键:用Object.create(Parent.prototype)避免调用Parent构造函数
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修复constructor指向

Child.prototype.play = function() {
  console.log(this.name + ' is playing');
};

登录后复制

⚠️ 注意点:

  • 不手动设置Child.prototype = Parent.prototype,否则修改子类原型会影响父类
  • 必须重设constructor,否则new Child().__proto__.constructor会指向Parent
  • 无法继承父类的静态方法(如Parent.staticMethod = () => {}),需额外拷贝

ES6继承:class + extends + super,语法更清晰

ES6引入class语法糖,但本质仍是基于原型的继承。使用extends声明继承关系,子类构造函数中必须调用super()——它负责初始化this并连接原型链。

立即学习“Java免费学习笔记(深入)”;

class Parent {
  constructor(name) {
    this.name = name;
  }
  say() {
    console.log('Hello from ' + this.name);
  }
  static create() {
    return new Parent('default');
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 必须!相当于Parent.call(this, name)
    this.age = age;
  }
  play() {
    console.log(this.name + ' is playing');
  }
  // 静态方法也能被继承
  static build() {
    return new Child('test', 10);
  }
}

登录后复制

✅ 优势明显:

标签: javascript es6 java app access 区别

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~