This is something that you probably don’t ever think about, but getters and setters are implicit on every javascript object. For example, if we take the following:
person = {};
person.name = 'Dave' //uses the implicit setter on the object
console.log(person.name) //uses the implicit getter
The above code is something that you have probably have seen very often in javascript. However, this doesn’t give you much control over how properties are accessed or defined. Suppose you wanted the name to be at least 10 characters long or you wanted to perform some other transformation on the string?
Enter the magic of getters and setters in Javascript. Using a getter and setter, you can define what happens when a particular property is accessed or defined. Since I’m a huge fan of typescript, let’s take a look at how to use typescript getter and setter.
export class Player {
private _name: string;
private _gamesWon: number;
private _id: string;
private _active: boolean;
constructor(name: string, id: string){
this._name = name;
this._gamesWon = 0;
this._id = id;
this._active = false;
}
public get active(): boolean {
return this._active;
}
public set active(value: boolean){
this._active = value;
}
public get playerName():string {
return this._name;
}
public get playerID(): string {
return this._id;
}
public get wins(): number {
return this._gamesWon;
}
}
Above, I list a class called Person. Within the class, I define get and set identifiers. In this particular case, it’s quite boring as I am not actually doing anything with them. None the less, that’s a simple class which demonstrates their use case. One important thing to remember is that when you define a get you need to have a corresponding set or the property will be assumed to be read-only. Also, using get and set will bind to the object’s property. So here’s how you would use it:
let p = new Player('Dave','uid');
p.playerName = 'Now a new name';
console.log(p.playerName);
There you have it!