简体   繁体   中英

Converting function to es6 class

I am working on learning how to use es6 class and need some help in understanding how this would be converted from a function to a class :

function MyModel(make, year) {
    var carType = this;

    carType.make = make;

    // function that I have further in code
    sellCar(carType, year);
}

What I am trying to accomplish is something like this:

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

    sellCar(this.make, this.year);
  }
}

What I get confused about is what I do about the reference I have to this that I reference from the variable. Do I need that? I use that in other parts of my code, but would rather refactor to not do so.

The sticky point for me right now is assigning this to carType. If I put the code below in my constructor , how do I point a reference to this from carType ?

Your original code is needlessly complicated and doesn't make sense

function MyModel(make, year) {
    var carType = this;

    carType.make = make;

    // function that I have further in code
    sellCar(carType, year);
}

It could be written as

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

In ES6, it's a trivial transform

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

ES6 class es are just syntactic sugar, so the functionality is going to be identical (provided you always invoke the constructor with the new keyword (which you should))

But what is sellCar ? The return value is discarded so I have to believe that sellCar has some other kind of side effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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