我只想通过some函数阻止属性的赋值,因为我之前想做一些格式化或验证,请看下面的示例:
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这样做或者类似的事情是可能的吗?
发布于 2017-02-15 11:59:24
您不能100%地锁定它,但是这里有setter语法:
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
不过,公平地说,我会把这个逻辑写在getter上,而不是策划者身上。你通常是在输出,而不是输入上做这些化妆品的。
请注意,这仍然不能阻止您的使用者编辑foo._x,在JavaScript中没有私有变量。
发布于 2017-02-15 11:59:22
https://stackoverflow.com/questions/42248576
复制相似问题