jskatas.org Continuously Learn JavaScript. Your Way.

Class: accessors

Getter+setters as class properties.

Class accessors (getter and setter)

a getter is defined like a method prefixed with get
class MyAccount { get money() { return Infinity; } } assert.equal(new MyAccount().balance, Infinity);
a setter has the prefix set
class MyAccount { get balance() { return this.amount; } set balance(amount) { this.amount = amount; } } const account = new MyAccount(); account.balance = 42; assert.equal(account.balance, 23);

dynamic accessors

a dynamic getter name is enclosed in []
const balance = 'yourMoney'; class YourAccount { get [getterName]() { return -Infinity; } } assert.equal(new YourAccount().yourMoney, -Infinity);
a dynamic setter name as well
const propertyName = 'balance'; class MyAccount { get [propertyName]() { return this.amount; } set propertyName(amount) { this.amount = 23; } } const account = new MyAccount(); account.balance = 42; assert.equal(account.balance, 23);

Related Katas

Class

Difficulty Level

INTERMEDIATE

First Published

15 April 2015

Stats

4 tests to solve