亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在類中實現獲取和設置

在類中實現獲取和設置

人到中年有點甜 2022-09-29 17:02:21
我通過w3s并發現了這一點。https://www.w3schools.com/Js/tryit.asp?filename=tryjs_classes_getters我理解所有值所采用的路徑,但是如何實現/為什么使用類中的get設置?我通過實施來學習,我將不勝感激。
查看完整描述

1 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

一個可能的用途是驗證。想象一下以這種方式實現的類: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.


查看完整回答
反對 回復 2022-09-29
  • 1 回答
  • 0 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號