W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <body> <h1>JavaScript Getter 和 Setter</h1> <p>创建完美的计数器:</p> <p id="demo"></p> <script> // 定义对象 var obj = {counter : 0}; // 定义 Setter 和 Getter Object.defineProperty(obj, "reset", { ????get : function () {this.counter = 0;} }); Object.defineProperty(obj, "increment", { ????get : function () {this.counter++;} }); Object.defineProperty(obj, "decrement", { ????get : function () {this.counter--;} }); Object.defineProperty(obj, "add", { ????set : function (value) {this.counter += value;} }); Object.defineProperty(obj, "subtract", { ????set : function (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>