JS的 setter方法

2009-03-31 10:43:19

仅支持 [b]Mozilla[/b] [b]方法1:[/b] * o.a - a number * o.b - a getter that returns o.a plus 1 * o.c - a setter that sets the value of o.a to half of its value [code]js> var o = {a:7, get b() {return this.a+1; }, set c(x) {this.a = x/2}}; [object Object] js> o.a; 7 js> o.b; 8 js> o.c = 50; js> o.a; 25 js> [/code] [b]方法2[/b] [code]var o = {'a':7, 'b' getter:(function () {return this.a + 1;}), 'c' setter:(function (x) {this.a = x / 2;})};[/code] [b]方法3[/b] [code]js> var d = Date.prototype; js> d.__defineGetter__("year", function() { return this.getFullYear(); }); js> d.__defineSetter__("year", function(y) { this.setFullYear(y); }); [/code] 注:Mozilla 3.0以前不支持HTML DOM元素,HTMLElement.prototype.__define[SG]etter__的实现会报错?文章上是这么说的! 先学习一下吧,渴求IE的 setter实现方法! 转:https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters