ES6 classes do not allow property declaration?

Asked

Viewed 119 times

9

I was experimenting with the class declaration syntax 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 class body? If it does not exist, what would be the justification for it to have been conceived like this?

  • 1

    @Renan But with get/set are not properties, are access methods (is that the term?). I wanted to know properties "for real".

2 answers

7

That’ll do, it’s called Public Class Fields and is in development phase 2 in the proposals of the TC39 (Panel of programmers that suggests new functionalities for Ecmascript).

If you’re 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();

6

There is no provision in ES6 for declaring properties directly in the class. The reason was the proposed maximum minimum 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.

Which translates as:

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

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

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

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

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

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

Source.

  • Thank you, the link is very enlightening! Especially this phrase: Is it possible that we can come up with a class syntax that we can all agree is Better than Nothing, and importantly, Leaves Possibilities open for Future Enhancement?

  • @bfavaretto - Not for that! As for the content, I agree: the goal was only to specify the minimum functional structure.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.