ES6 classes do not allow declaration of properties?

8

I was experimenting with the class declaration syntax of ES6 / ES- 2015, and could not declare properties, only methods:

class Teste {
    constructor() {

    }

    metodo() {

    }

    // não funciona:
    //propriedade: valor

}

Is there any way to declare instance properties in the body of the class? If it does not exist, what would be the justification for it being designed like this?

    
asked by anonymous 04.01.2017 / 17:22

2 answers

6

This will arrive, it's called Public Class Fields and is in Phase 2 development in the TC39 proposals (developers panel suggesting new features for ECMAScript).

If you are using a compiler with Babel you can use it like this:

class Animal {
  familia = 'Domésticos'
  buscarNome = () => console.log(this.nome);
  buscarFamilia = () => console.log(this.familia);
  darNome(nome) {
    this.nome = nome;
  }
}

const bobby = new Animal();
bobby.darNome('bobby');
bobby.buscarNome();
bobby.buscarFamilia();
    
04.01.2017 / 17:32
5

There is no provisioning in ES6 for declaration of properties directly in the class. The reason was the proposal for maximally minimal classes .

The key point is this:

  

There is (intentionally) no direct declarative way to define either prototype data properties (other than methods), class properties, or instance property.

That translates as:

  

Intentionally, there is no direct declarative way of defining either prototypical properties (apart from methods), class properties, or instance properties.

Properties must be declared outside the declaration, or in the constructor:

class Teste {
  constructor() {
    this.propriedade = 'valor';
  }

  metodo() {
    console.log(this.propriedade);
  }
}

var oTeste = new Teste();
oTeste.metodo();

ES7, however, has a proposal for concise statement of properties .

Source.

    
04.01.2017 / 17:41