Question on ES6 syntax.

The ES6 notation of classes provides for the elegant creation of static methods, getters / setters, and it is also convenient to describe all methods for class instances in a block instruction.

And what about setting the "flags" (writable, configurable, etc) for the properties of the generated objects? Is it true that additional wrappers are still needed?

'use strict'; function User(name, age) { class User { constructor() { this.name = name; } } let user = new User(name); Object.defineProperties(user, { gender: { value: 'male' }, age: { get: function() { return age; }, set: function(value) { alert('Молодость не вернешь!'); return false; } } }); return user; } const user = new User('Vasya', 23); user.age = 16; console.log(user.age); 

    1 answer 1

    In the example you created, new has no meaning. Because no instance of the external class User returned.

     "use strict"; class User { constructor(name, age) { this.name = name; Object.defineProperty(this, 'age', { value: age, writable: false }); } }; var user = new User('a', 123); alert('user has age ' + user.age); try { user.age = 12; //тут выбросится исключение, возраст не изменится } catch(e){ alert('Ошибка при изменении возраста'); } alert('after trying change, age = ' + user.age); 

    In this case, you do not have the option to make an alert out of the box, but the property turns out just read-only. If you want, you can beat the getter, setter in the same way.

    In general, apparently, in ES2015 there is no way to beautifully declare a class field as readonly. However, decorators will appear in ES2016, which will allow you to do this quite succinctly.

    • you are wrong, it will be returned exactly the object that is returned, so rather there is no point in the operator new - Grundy
    • hmm, yes, I didn’t wake up apparently when I wrote - NumminorihSF