繁体   English   中英

将函数转换为es6类

[英]Converting function to es6 class

我正在学习如何使用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 ,我怎么指向引用thiscarType

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

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只是语法糖,因此功能将是相同的(前提是您始终使用new关键字调用构造函数(应该如此))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM