W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <body> <h1>JavaScript Class Gettter/Setter</h1> <p>演示如何在类中添加 getter 和 setter,以及如何使用 getter 获取属性值。</p> <p id="demo"></p> <script> class Car { constructor(brand) { this.carname = brand; } get cnam() { return this.carname; } set cnam(x) { this.carname = x; } } let myCar = new Car("Ford"); document.getElementById("demo").innerHTML = myCar.cnam; </script> </body> </html>