JavaScript类中的获取器和设置器?
类允许使用getter和setter。对属性使用getter和setter是明智的,尤其是如果您想在返回值之前或在设置它们之前对值进行特殊处理。要在类中添加getter和setter,请使用get和set关键字。
示例
<html>
<body>
<p id="method"></p>
<script>
class Company {
constructor(brand) {
this.Compname = brand;
}
get name() {
return this.Compname;
}
set name(x) {
this.Compname = x;
}
}
myName = new Company("Nhooo");
document.getElementById("method").innerHTML = myName.Compname;
</script>
</body>
</html>输出结果
Nhooo
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短