如何实现类?

29 阅读1分钟

一、使用原型来实现

function Dog(name) {
  this.name = name
  this.legNumber = 4
}
Dog.prototype.say = function() {console.log(`汪汪汪,我是一只名叫${this.name}的狗`)}
const d1 = new Dog("旺财") // dog函数就是一个类
d1.say()

二、

class Dog {
  constructor(name){
    this.name = name
    this.legNum = 4
  }
  say(){console.log(`汪汪汪,我是一只名叫${this.name}的狗`)}
}
const d1 = new Dog("旺财")
d1.say()