构造函数与类

89 阅读1分钟

一、构造函数写法

function Person(name = '匿名', age = 0) {
   this.name = name
   this.age = age
}

Person.prototype = {
  constructor: Person,     
  
  sayHi() {
    console.log(`你好,我是${this.name}`)
  },
  run() {
    console.log(`${this.name} 在跑步`)
  }
}

const f1 = new Person('fang',18) 
f1.sayHi()
f1.run()



构造函数写法的共有属性部分还可以放在外部:


function Person(name = '匿名', age = 0) {
  this.name = name
  this.age = age
}

Person.prototype.sayHi = function() {
   console.log(`你好,我是${this.name}`)
}

Person.prototype.run = function() {
  console.log(`${this.name} 在跑步`)
}


二、class(类)写法

class Person {
  constructor(name = '匿名', age = 0) {
    this.name = name
    this.age = age
  }

  sayHi() {
    console.log(`你好,我是${this.name}`)
  }

  run() {
    console.log(`${this.name} 在跑步`)
  }
}

三、注意

注意class写法的共有属性部分不支持非函数属性!
箭头函数不能作为构造函数, 它不支持this 不自带prototype