方法一:使用原型
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayHi = function() {
console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
}
const xiaoming = new Person('小明', 16)
xiaoming.sayHi()
方法二: 使用 class
class Person{
constructor(name, age){
this.name = name
this.age = age
}
sayHi(){
console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
}
}
const xiaoming = new Person('小明', 16)
xiaoming.sayHi()