W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <body> <h1>JavaScript Getter 和 Setter</h1> <p>创建完美的计数器对象:</p> <p id="demo"></p> <script> var obj = { ?? counter : 0, ?? get reset() { ?????? this.counter = 0; ?? }, ?? get increment() { ?????? this.counter++; ?? }, ?? get decrement() { ?????? this.counter--; ?? }, ?? set add(value) { ?????? this.counter += value; ?? }, ?? set subtract(value) { ?????? this.counter -= value; ?? } }; // 操作计数器: obj.reset; obj.add = 5; obj.subtract = 1; obj.increment; obj.decrement; // 显示计数器: document.getElementById("demo").innerHTML = obj.counter; </script> </body> </html>