-2

I would like to build a ES6 class which can read it's child properties already on constructor level. In the other words I would like to have this specs passing:

class Collection {
  model = 'model';

  constructor() {
    // I JUST DO A SIMPLE ASSIGNMENT HERE
    // BUT IN THE FINAL VERSION I WOULD
    // LIKE TO DO SOME MORE ADVANCED
    // CALCULATIONS HERE
    this.modelCopy = this.model;
  }

  getModel() {
    return this.model;
  }
}

class MyCollection extends Collection {
  model = 'myModel';
}

it('this is passing', () => {
  expect(new Collection().getModel()).toBe('model');
  expect(new MyCollection().getModel()).toBe('myModel');
});

it('this is NOT passing', () => {
  expect(new Collection().modelCopy).toBe('model');
  // this fails because new MyCollection().modelCopy === 'model'
  expect(new MyCollection().modelCopy).toBe('myModel');
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
michaltaberski
  • 633
  • 1
  • 10
  • 17
  • Can you clarify what is the current behavior and what is the expected one? Are the assertions the former? Then what is the latter. – Nurbol Alpysbayev Dec 21 '18 at 08:57
  • Also `model = 'myModel';` is not valid JS – Nurbol Alpysbayev Dec 21 '18 at 08:59
  • @NurbolAlpysbayev the current behavior is that `new MyCollection().modelCopy` returns `'model'`. While I would like to get `myModel`. @skyboyer answer seems to explain the issue clearly. I can't achieve what I want with class properties. I will need to think about different construction. – michaltaberski Dec 21 '18 at 09:33
  • If you are using class properties then your not using ES6. – Felix Kling Dec 21 '18 at 10:26

1 Answers1

1

class properties are not handled natively. So far they are transformed by babel's plugin-proposal-class-properties.

And if this plugin transpiles class properties into values are initialized after constructor() is called there is nothing you can do about that.

I've found an issue in their github that cleary states for this approach:

Yes. It can't be done before calling super() because this is the return value of super. Before, this doesn't exists so class fields can't be defined.

[UPD] spec is here: tc39proposal-class-fields but I've failed to find out information if such approach is proposed to follow in native implementation or not.

skyboyer
  • 22,209
  • 7
  • 57
  • 64