Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 492
galarant Avatar asked Mar 09 '16 23:03

galarant


People also ask

Which JavaScript feature is the alternative to the ES6 classes?

Top Alternatives to ES6 js or Apache CouchDB. It is a prototype-based, multi-paradigm scripting language that is dynamic,and supports object-oriented, imperative, and functional programming styles. ... It adds syntactic sugar inspired by Ruby, Python and Haskell in an effort to.

Is ES6 object-oriented?

In this course, Object-oriented Programming in JavaScript - ES6, you will learn this new syntax and create many different kinds of classes. You'll learn all the features of JavaScript classes including working with constructors, prototypes, inheritance, and simulating public, private, and static members.

What are classes in ES6?

There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.


1 Answers

Yup, it's called a getter.

class A {
  my_method() {
    return "I am a return value.";
  }

  get my_property() {
    return "I am also a return value.";
  }
}
like image 111
Mike Cluck Avatar answered Oct 02 '22 12:10

Mike Cluck