原型继承和 Class 继承

韩小韩
2022-10-12 / 0 评论 / 455 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年04月18日,已超过377天没有更新,若内容或图片失效,请留言反馈。

⾸先先来讲下 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

寄⽣组合继承

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

评论 (0)

取消