MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

继承再问是孙子 #61

Open MJingv opened 4 years ago

MJingv commented 4 years ago

用call继承

function Parent () {
  this.name = 'parent'
}

Parent.prototype.do = function () {
  console.log(1)
}

function Child () {
  this.name = 'child'
  Parent.call(this)
}

let c = new Child()
console.log(c)
MJingv commented 4 years ago

用原型链

function Parent () {
  this.name = 'parent'
}

Parent.prototype.do = function () {
  console.log(1)
}

function Child () {
  this.name = 'child'
}

Child.prototype = new Parent()
let c = new Child()
console.log(c)
MJingv commented 4 years ago

call+原型链


function Parent () {
  this.name = 'parent'
}

Parent.prototype.do = function () {
  console.log(1)
}

function Child () {
  Parent.call(this)
  this.name = 'child'
}

Child.prototype = new Parent() //多次调用
let c = new Child()
console.log(c)
MJingv commented 4 years ago

寄生组合


function Parent () {
  this.name = 'parent'
}

Parent.prototype.do = function () {
  console.log(1)
}

function Child () {
  Parent.call(this)
  this.name = 'child'
}

Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
let c = new Child()
console.log(c.__proto__)
MJingv commented 4 years ago

class