正在将函数转换为es6类

Converting function to es6 class

本文关键字:es6 转换 函数      更新时间:2023-09-26

我正在学习如何使用es6 class,需要一些帮助来了解如何将其从function转换为class:

function MyModel(make, year) {
    var carType = this;
    carType.make = make;
    // function that I have further in code
    sellCar(carType, year);
}

我想完成的是这样的事情:

class MyModel {
  constructor(make, year) {
    this.make = make;
    this.year = year;
    sellCar(this.make, this.year);
  }
}

我感到困惑的是,我对从变量中引用的this的引用做了什么。我需要那个吗?我在代码的其他部分使用它,但宁愿重构也不这样做

我现在的难点是将this分配给carType。如果我把下面的代码放在我的constructor中,我如何从carType指向this

您的原始代码不必要地复杂,并且没有意义

function MyModel(make, year) {
    var carType = this;
    carType.make = make;
    // function that I have further in code
    sellCar(carType, year);
}

它可以写成

function MyModel(make, year) {
  this.make = make;
  sellCar(this, year);
}

在ES6中,它是一个琐碎的转换

class MyModel {
  constructor (make, year) {
    this.make = make;
    sellCar(this, year);
  }
}

ES6classes只是语法糖,因此功能将是相同的(前提是您总是用new关键字调用构造函数(您应该这样做))

但什么是sellCar?返回值被丢弃了,所以我不得不相信sellCar还有其他一些副作用。