运行 ❯
获取您
自己
的网站
×
更改方向
保存代码
更改主题,暗色/亮色
前往 Spaces
<!DOCTYPE html> <html> <body> <h1>JavaScript Class Getter/Setter</h1> <p>Using an underscore character is common practice when using getters/setters in JavaScript, but not mandatory, you can name them anything you like, but not the same as the property name.</p> <p id="demo"></p> <script> class Car { constructor(brand) { this._carname = brand; } get carname() { return this._carname; } set carname(x) { this._carname = x; } } const myCar = new Car("Ford"); document.getElementById("demo").innerHTML = myCar.carname; </script> </body> </html>