首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript中的Setters

Javascript中的Setters
EN

Stack Overflow用户
提问于 2017-02-15 11:49:38
回答 3查看 43关注 0票数 0

我只想通过some函数阻止属性的赋值,因为我之前想做一些格式化或验证,请看下面的示例:

代码语言: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

这样做或者类似的事情是可能的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-02-15 11:59:24

您不能100%地锁定它,但是这里有setter语法:

代码语言:javascript
复制
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中没有私有变量。

票数 2
EN

Stack Overflow用户

发布于 2017-02-15 11:59:22

这是可能的!

如果您查看用于集的mdn页面,您将得到一些关于如何解决问题的好线索。

一般的要点是,您可以将set propName定义为设置新值的函数,并且在该函数中可以应用任何转换!

票数 1
EN

Stack Overflow用户

发布于 2017-02-15 12:01:49

您可以定义访问器,但不能将它们与值一起使用。Mozilla文档

不可能同时将getter绑定到属性并使该属性实际保存一个值。

我已经用数组示例回答了这个问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42248576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档