Object Oriented Typescript #3 - Encapsulation, and private variables

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

This course is awesome, thanks for sharing

sguitas
Автор

It's weird, people always confuse actual setters and getters with regular methods. The proper way to write this is:

get health() {
return this.propertyHealth
}

set health(newHealth) {
this.propertyHealth = newHealth
}

kresimircosic
Автор

class Player {
private _health: number;
private _speed: number;

constructor(health: number, speed: number) {
this._health = health;
this._speed = speed;
}

get health(): number {
return this._health;
}

set health(health: number) {
if (health < 0) {
console.log("Health can't be less than 0");
return
}

this._health = health;
}

get speed(): number {
return this._speed;
}

set speed(speed: number) {
this._speed = speed;
}
}

const mario = new Player(8, 10);
mario.health = -3.14; // Will throw "Health can't be less than 0"
console.log(mario.health); // Will print 8 because the setter prevented setting health to -3.14
mario.speed = 15; // Will set speed to 15
console.log(mario.speed); // Will print 15

hasaniqbal