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 { //w w w. j a v a 2 s. 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"); console.log(whiteJet.color); // white
Here, we are computing the method name and getter and setter accessor property names inside the class definition by wrapping them with [ ].