简体   繁体   中英

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?

TL;DR - You can't, you should do it the same way as you would do in ES6.

What you do with the properties is part of the class fields declaration proposal , method declarations like you want are not a part of that proposal.

The proposal is currently in stage 3, which means that it's not yet part of the official ECMAScript specifications, but could be coming soon (maybe in ES2019?). So I would even advise against the class properties you used in the example because the syntax of it could still change.

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.

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