2020年10月20日(javascript class)


OOP 即 面向对象编程 (Object Oriented Programming),一些编程语言如 Java 、C++ 就是基于 OOP 的核心概念 class 开发出来。

javascript也有class的概念,ES6 之后,JavaScript 也引入了 class 关键字用于声明一个类

class Person {
  constructor (name) {
    this.name = name
  }
  sayHello () {
    console.log(`${this.name} says hello`)
  }
}

但需要注意的是,这样声明出来的类其实在底层使用了 JavaScript 的函数 和 原型链 来模拟类的行为,以上代码非常接近于,可以看出sayHello并不是Person内部封装的方法,只是普通方法,赋值到了person的原型上,因此,sayHello函数里的 this 对应的是调用时的上下文而不是定义时的上下文

function Person (name) {
  this.name = name
}
Person.prototype.sayHello = function () {
  console.log(`${this.name} says hello`)
}

解决this问题

1.**bind()**方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数

class Person {
  constructor (name) {
    this.name = name
    this.sayHello = this.sayHello.bind(this); // 在构造器里显式调用 bind 函数绑定 this
  }

  sayHello () {
    console.log(`${this.name} says hello`)
  }
}

2.箭头函数

class Person {
  constructor(name) {
    this.name = name
  }
  sayHello = () => {
    console.log(`${this.sayHello} says hello`)
  }
}

他等效于

class Person {
  constructor(name) {
    this.name = name
    this.sayHello = () => {
      console.log(`${this.name} says hello`)
    }
  }
}

这个方法不在原型链上,即 Person.prototype.sayHello的值是undefined ,所以这个类的子类并不能使用 super.sayHello() 调用到父类这个方法


Author: wxy
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source wxy !
  TOC