Is there an equivalent to Python-style class properties in ES6?

Viewed 1765

Python classes have this neat feature where you can decorate a class method with the @property decorator, which makes the method appear as a statically-valued member rather than a callable. For example, this:

class A(object):

    def my_method(self):
        return "I am a return value."

    @property
    def my_property(self):
        return "I am also a return value."

results in the following behavior:

>>> a = A()
>>> a.my_method()
'I am a return value.'
>>> a.my_property
'I am also a return value.'

So finally, my question: is there any built-in syntax that provides similar behavior in ES6 classes? I'm not an expert on the documentation (yet) but so far I don't see anything that provides this type of functionality.

2 Answers

To attempt correct encapsulation, use a private variable (with __ prefix - note as a convention, I use __ for private and _ for protected) and differentiate your private variable from the public (getter) variable:

export default class AssetHelper {

  __canvasWidth = 0;

  constructor() {
    this.__canvasWidth = 200;
  }

  get canvasWidth() {
    return this.__canvasWidth;
  }
}

Then at some point in the code...

let assetHelper = new AssetHelper();
console.log(assetHelper.canvasWidth)
Related