Skip to content

实现类的继承

js
// 题目描述:实现一个你认为不错的 js 继承方式
// 寄生组合继承
function Parent(name) {
  this.name = name
  this.say = () => {
    console.log(111)
  }
}

Parent.prototype.play = () => {
  console.log(222)
}

function Children(name) {
  Parent.call(this)
  this.name = name
}

Children.prototype = Object.create(Parent.prototype)
Children.prototype.constructor = Children

let child = new Children('111')
console.log(child.name)
child.say()
child.play()
js
// 寄生组合继承
function Person(obj) {
  this.name = obj.name
  this.age = obj.age
}

Person.prototype.add = function (value) {
  console.log(value)
}
function Children(obj) {
  Person.call(this, obj)
  this.sex = obj.sex
}

Children.prototype = Object.create(Person.prototype)
Children.prototype.constructor = Children

Children.prototype.play = function (value) {
  console.log(value)
}
js
class People {
  constructor(name = 'water', age = '27') {
    this.name = name
    this.age = age
  }
  eat() {
    console.log(`${this.name} ${this.age} eat food`)
  }
}

class Woman extends People {
  constructor(name = 'ren', age = '27') {
    super(name, age)
  }
  eat() {
    super.eat()
  }
}
js
// 原型链继承
function Parent() {
  this.name = 'parent'
  this.play = [1, 2, 3]
}

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

Child.prototype = new Parent()

console.log(new Child())
// 借用构造函数继承
function Parent() {
  this.name = 'parent'
  this.getName = function () {
    return this.name
  }
  this.getName3 = function () {
    return this.name
  }
}
Parent.prototype.getName2 = function () {
  console.log(this.name)
}
function Child() {
  Parent.call(this)
  this.type = 'child'
}

console.log(new Child())

// 组合继承
function Parent() {
  this.name = 'parent'
  this.play = [1, 2, 3]
}

Parent.prototype.getName = function () {
  return this.name
}

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

Child.prototype = new Parent()
Child.prototype.constructor = Child

const s1 = new Child()
const s2 = new Child()
s1.play.push(4)

console.log(s1.play, s2.play)
console.log(s1.getName())
console.log(s2.getName())
// 原型继承

let parent4 = {
  name: 'parent4',
  friends: ['p1', 'p2', 'p3'],
  getName: function () {
    return this.name
  },
}

let person4 = Object.create(parent4)
person4.name = 'tom'
person4.friends.push('jerry')

let person5 = Object.create(parent4)
person5.friends.push('lucy')

console.log(person4.name)
console.log(person4.name === person4.getName())
console.log(person5.name)
console.log(person4.friends)
console.log(person5.friends)

// 寄生组合继承
function Parent() {
  this.name = 'parent'
  this.play = [1, 2, 3]
}

Parent.prototype.getName = function () {
  return this.name
}

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

Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

如有转载或 CV 的请标注本站原文地址