方法一:使用原型

  1. function Person(name, age) {
  2. this.name = name
  3. this.age = age
  4. }
  5. Person.prototype.sayHi = function() {
  6. console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
  7. }
  8. const xiaoming = new Person('小明', 16)
  9. xiaoming.sayHi()

方法二: 使用 class

  1. class Person{
  2. constructor(name, age){
  3. this.name = name
  4. this.age = age
  5. }
  6. sayHi(){
  7. console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
  8. }
  9. }
  10. const xiaoming = new Person('小明', 16)
  11. xiaoming.sayHi()