Javascript - Class Computed Method Names


Methods and getter/setter accessor properties inside a class can have computed names.

The computed method names can be wrapped with [ ]:


const methodName = "getColor"; 
const propName = "color"; 

class Bus { // ww w.  j a v  a  2s.c  o  m
constructor(color) { 
                this._color = color 

        [methodName]() { 
                return this._color; 

        get [propName]() { 
                return this[`_${propName}`]; 

        set [propName](value) { 
                return this[`_${propName}`] = value; 
const whiteJet = new Bus("white"); 
// white


Here, we are computing the method name and getter and setter accessor property names inside the class definition by wrapping them with [ ].