【问题标题】:Implementation of get and set in a class类中get和set的实现
【发布时间】:2020-06-11 20:32:52
【问题描述】:

我正在浏览 w3s 并找到了这个。 https://www.w3schools.com/Js/tryit.asp?filename=tryjs_classes_getters

我了解所有值所采用的路径,但这将如何实现/为什么在类中设置会被使用?我通过实施来学习,我将非常感谢一个例子。

【问题讨论】:

    标签: javascript class get set


    【解决方案1】:

    一种可能的用途是验证。想象一下以这种方式实现的类Account

    class Account {
      #username;
      #password;
      constructor(name) {
        this.#username = name;
      }
      get username() {
        return this.#username;
      }
      set password(password) {
        if (password.length < 10) {
          throw "Password must be at least 10 characters long!";
        }
        this.#password = password;
      }
      get password() {
        throw "Forgotten passwords cannot be retrieved!  Please make a new one instead.";
      }
    }
    

    我可以这样创建一个新帐户:

    const myAccount = new Account('John Doe');
    

    如果我尝试将密码设置为不可接受的短长度,我会收到错误消息:

    myAccount.password = 'hunter2'; // Password must be at least 10 characters long!
    

    如果我在忘记密码后尝试找回密码,我会再次收到错误:

    console.log(myAccount.password); // Forgotten passwords cannot be retrieved!  Please make a new one instead.
    

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      相关资源
      最近更新 更多