zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

132. 将类改写成函数 #189

Open zlx362211854 opened 4 years ago

zlx362211854 commented 4 years ago

将下面类写法改成函数写法

class A {
  constructor() {
    this.c = () => {}
    this.d = function() {}
  }
  a = () => {}
  b() {}
}
zlx362211854 commented 4 years ago
function A() {
  this.a = () => {}
  this.c = () => {}
  this.d = function() {}
}
A.prototype.b = function() {}

首先,constructor内部的属性c,d在作用在其函数本身上,其次箭头函数a由于指向外部域,所以也指向构造方法,直接定义的函数b由于是普通函数,会绑定在类的prototype上。

goldEli commented 4 years ago

JavaScript 可以通过原型来继承父级的属性,所以可以用原型来改写类:


    function A() {
      this.c = () => {console.log(this)}
      this.d = function() {console.log(this)}
      /**
       * A.prototype.a = () => {console.log(this)} 
       * 如果把箭头函数挂到原型上,那么 this 会指向全局,为了绑定 this,所以将 a 方法写到函数内部
       * 
      */
      this.a = () => {console.log(this)}
    }

    A.prototype.b = function() {console.log(this)}```