构造函数与原型方法

  1. // class 关键词
  2. // function Person (name) {
  3. // this.name = name
  4. // }
  5. // Person.prototype.say = function () {
  6. // console.log(`hi, my name is ${this.name}`)
  7. // }
  8. class Person {
  9. constructor (name) {
  10. this.name = name
  11. }
  12. say () {
  13. console.log(`hi, my name is ${this.name}`)
  14. }
  15. }
  16. const p = new Person('tom')
  17. p.say()

静态方法

  1. // static 方法
  2. class Person {
  3. constructor (name) {
  4. this.name = name
  5. }
  6. say () {
  7. console.log(`hi, my name is ${this.name}`)
  8. }
  9. static create (name) {
  10. return new Person(name)
  11. }
  12. }
  13. const tom = Person.create('tom')
  14. tom.say()

继承

  1. // extends 继承
  2. class Person {
  3. constructor (name) {
  4. this.name = name
  5. }
  6. say () {
  7. console.log(`hi, my name is ${this.name}`)
  8. }
  9. }
  10. class Student extends Person {
  11. constructor (name, number) {
  12. super(name) // 父类构造函数
  13. this.number = number
  14. }
  15. hello () {
  16. super.say() // 调用父类成员
  17. console.log(`my school number is ${this.number}`)
  18. }
  19. }
  20. const s = new Student('jack', '100')
  21. s.hello()