将函数转换为es6类

时间:2016-07-16 19:43:16

标签: javascript ecmascript-6

我正在努力学习如何使用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中,如何从this指向carType的引用?

1 个答案:

答案 0 :(得分:2)

你的原始代码是不必要的复杂而且没有意义

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);
  }
}

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

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

相关问题