Javascript 中的二传手
Setters in Javascript
我想阻止仅通过设置名称函数来分配属性,因为我想在之前进行一些格式化或验证,请看示例:
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
可以做这个或类似的事情吗?
确实有可能!
如果您查看 mdn page for set,您将获得一些很好的解决问题的线索。
一般要点是您可以将 set propName
定义为设置新值的函数,并且在该函数中您可以应用任何转换!
你不能 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 而不是 setter 上使用这种逻辑。您通常在输出而不是输入上做这些装饰性的事情。
请注意,仍然 不会阻止您的用户编辑 foo._x
,JavaScript 中没有私有变量。
您可以定义访问器,但不能将它们与值一起使用。 Mozilla documentation:
It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value
我已经用 example for arrays 回答了这个问题。
我想阻止仅通过设置名称函数来分配属性,因为我想在之前进行一些格式化或验证,请看示例:
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
可以做这个或类似的事情吗?
确实有可能!
如果您查看 mdn page for set,您将获得一些很好的解决问题的线索。
一般要点是您可以将 set propName
定义为设置新值的函数,并且在该函数中您可以应用任何转换!
你不能 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 而不是 setter 上使用这种逻辑。您通常在输出而不是输入上做这些装饰性的事情。
请注意,仍然 不会阻止您的用户编辑 foo._x
,JavaScript 中没有私有变量。
您可以定义访问器,但不能将它们与值一起使用。 Mozilla documentation:
It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value
我已经用 example for arrays 回答了这个问题。