在类中实现获取和设置

我通过w3s并发现了这一点。https://www.w3schools.com/Js/tryit.asp?filename=tryjs_classes_getters

我理解所有值所采用的路径,但是如何实现/为什么使用类中的get设置?我通过实施来学习,我将不胜感激。



人到中年有点甜
浏览 93回答 1
1回答

胡说叔叔

一个可能的用途是验证。想象一下以这种方式实现的类:Accountclass Account {&nbsp; #username;&nbsp; #password;&nbsp; constructor(name) {&nbsp; &nbsp; this.#username = name;&nbsp; }&nbsp; get username() {&nbsp; &nbsp; return this.#username;&nbsp; }&nbsp; set password(password) {&nbsp; &nbsp; if (password.length < 10) {&nbsp; &nbsp; &nbsp; throw "Password must be at least 10 characters long!";&nbsp; &nbsp; }&nbsp; &nbsp; this.#password = password;&nbsp; }&nbsp; get password() {&nbsp; &nbsp; throw "Forgotten passwords cannot be retrieved!&nbsp; Please make a new one instead.";&nbsp; }}我可以创建一个新帐户,如下所示: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!&nbsp; Please make a new one instead.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript