JS如何实现类?

52 阅读1分钟

原型实现

function Person(name){
  this.name = name
  this.eyes = 2
}
Person.prototype.say = function(){
  console.log(`我是${this.name},我有${this.eyes}只眼`)
}
Person.prototype.kind = '人'

有一个问题:**你不能同时修改多个prototype,**比如

Person.prototype = {
  ...
  ...
}
因为在JS函数(非箭头函数)中
Person.prototype.constructor = Person
// 你那样做 会抹杀掉本身

class实现

class Person{
  constructor(name){
    this.name = name
    this.eyes = 2
  }
  say(){
    console.log(`我是${this.name},我有${this.eyes}只眼`)
  }
}
const p = new Person('colin')
p.say() //我是colin,我有2只眼