Reputation: 542
I want to block the assignment of properties only by the set name function because I want to do some formatting or validation before, look the example:
class Animal {
construct(name){
this.name = name;
return this;
}
setName(name){
this.name = name;
}
getName(){
return this.name;
}
}
class Dog extends Animal {
constructor(name){
super(name);
return this;
}
setName(name){
this.name = name.charAt(0).toUpperCase() + name.slice(1);
}
}
const dog = new Dog();
dog.setName('joe');
console.log(dog.getName()); //Joe
dog.name = 'Bill'; // I wish this type of assignment would not work
console.log(dog.getName()); //Bill
It is possible to do this or something similar ?
Upvotes: 0
Views: 54
Reputation: 23826
You can define accessors but you can not have them together with values. Mozilla documentation:
It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value
I answered this already with an example for arrays.
Upvotes: 1
Reputation: 174967
You can't lock it down 100%, but there is the setter syntax:
class Foo {
constructor(x) {
this.x = x;
}
set x(newX) {
this._x = newX.charAt(0).toUpperCase() + newX.slice(1);
}
get x() {
return this._x;
}
}
const foo = new Foo('hello');
console.log(foo.x); // Hello
foo.x = 'goodbye';
console.log(foo.x); // Goodbye
To be fair, though, I'd have this logic on the getter, rather than the setter. You generally do these cosmetic things on output, not on input.
Note that this still doesn't prevent your consumer from editing foo._x
, there are no private variables in JavaScript.
Upvotes: 2
Reputation: 2034
It is possible indeed!
If you look at the mdn page for set, you'll get some nice clues to how to solve your problem.
The general gist is that you can define set propName
as a function to which the new value is set, and within that function you can apply any transformation!
Upvotes: 1