Is it possible to make a private 'set' in js?
class Player{
constructor(nickname){
this._nickname = nickname;
}
get _nickname(){
return value;
}
set _nickname(value){
this.nickname = value;
}
}
Is it possible to make a private 'set' in js?
class Player{
constructor(nickname){
this._nickname = nickname;
}
get _nickname(){
return value;
}
set _nickname(value){
this.nickname = value;
}
}
You can use a proxy:
class Player{
constructor(nickname) { this._nickname = nickname; }
get nickname() { return this._nickname; }
set nickname(value) { this._nickname = value; }
}
function makePlayer(nickname) {
const player = new Player(nickname);
return new Proxy(player, {
set(target, property, value, receiver) {
if (property === 'nickname' || property === '_nickname')
throw "Can't set nickname or _nickname!";
target[property] = value;
},
get(target, property, receiver) {
console.log("property is", property);
if (property === '_nickname')
throw "Can't get _nickname!";
return target[property];
}
});
}
const player = makePlayer("Bob");
console.log(player.nickname);
player.nickname = "Sally"; // Can't set nickname or _nickname!
The set nickname(value)
in the definition allows you to say this.nickname = "Donald";
within the class methods, which is what I assume you want to do, and have the setter handle the setting. The proxy intercepts gets and sets on nickname
and _nickname
and blocks them as necessary. You can export only makePlayer
and keep Player
private in order to prevent the bad guys from instantiating Player
directly and circumventing your elaborate privacy mechanisms.