W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <body> <h1>JavaScript ES5 对象</h1> <p>一个计数器实例</p> <p id="demo"></p> <script> // 定义对象 const obj = {counter:0}; // 定义 setter 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 (i) {this.counter -= i;} }); // 操作计数器: obj.reset; obj.add = 5; obj.subtract = 1; obj.increment; obj.decrement; // 打印 document.getElementById("demo").innerHTML = "当前对象计数为:" + obj.counter; </script> </body> </html>