Search code examples
javascriptecmascript-2016

How can we call a method inside class in ES7?


ES6 Simple example

class MyClass extends SuperClass {
  constructor() {
    super()
    this.myProperty = 'myProperty'
  }
}

In ES7, the preceding example can be written as:

class MyClass extends SuperClass {
  myProperty = 'myProperty'
}

In ES6 we can call a method inside constructor like this:

import myMethod from './myMethod'
class MyClass extends SuperClass {
  constructor() {
    super()
    myMethod()
  }
}

In ES7, How can we call a method that will be noted as constructor method?

import myMethod from './myMethod'
class MyClass extends SuperClass {
  myMethod()
}

Syntax error: Unexpected token, expected {


PS: I know I can still use the ES6 syntax. But is there a way without writing constructor?


Solution

  • Here's a possible way of achieving that without writing a constructor, but it's not something you should want to do - class fields are meant for properties that are assigned to the instantiated object. If it's not meant to be a property of the object, it should be done in the constructor instead.

    function myMethod() {
      console.log('method running');
    }
    
    class SuperClass { }
    class MyClass extends SuperClass {
      someIrrelevantPropName = (myMethod(), undefined)
    }
    const someInstantiation = new MyClass();

    Note that this will actually assign undefined to someInstantiation.someIrrelevantPropName. That is, 'someIrrelevantPropName' in someInstantiation will evaluate to true, so this comma operator exploit is not without side-effects.