本站资源是站长搜集整理而成,版权均归原作者所有,若无意中侵犯到您的版权利益,请来信联系我们删除! 本站所有资源只用于研究学习,不得作为商业用途、非法谋取暴利,否则,一切后果均由自己承担!

首页 > 教程

原型继承和 Class 继承

  • slbcun
  • 2025-04-07
  • 798 ℃

⾸先先来讲下 class ,其实在 JS 中并不存在类, class 只是语法糖,本质还是函数

class Person {}
Person instanceof Function; // true

组合继承

function Parent(value) {
  this.val = value;
}
Parent.prototype.getValue = function () {
  console.log(this.val);
};

function Child(value) {
  Parent.call(this, value);
}
Child.prototype = new Parent();
const child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // true

以上继承的⽅式核⼼是在⼦类的构造函数中通过 Parent.call(this) 继承⽗类的属性, 然后改变⼦类的原型为 new Parent() 来继承⽗类的函数。 这种继承⽅式优点在于构造函数可以传参,不会与⽗类引⽤属性共享,可以复⽤⽗类的函 数,但是也存在⼀个缺点就是在继承⽗类函数的时候调⽤了⽗类构造函数,导致⼦类的原 型上多了不需要的⽗类属性,存在内存上的浪费


寄⽣组合继承

这种继承⽅式对组合继承进⾏了优化,组合继承缺点在于继承⽗类函数时调⽤了构造函数,我们只需要优化掉这点就⾏了

function Parent(value) {
  this.val = value;
}
Parent.prototype.getValue = function () {
  console.log(this.val);
};
function Child(value) {
  Parent.call(this, value);
}
Child.prototype = Object.create(Parent.prototype, {
  constructor: {
    value: Child,
    enumerable: false,
    writable: true,
    configurable: true,
  },
});
const child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // true

class继承

class Parent {
  constructor(value) {
    this.val = value;
  }
  getValue() {
    console.log(this.val);
  }
}
class Child extends Parent {
  constructor(value) {
    super(value);
    this.val = value;
  }
}
let child = new Child(1);
child.getValue(); // 1
child instanceof Parent; // true


文章评论 (0)

    • 这篇文章还没有收到评论,赶紧来抢沙发吧~


Top