第一种算是比较常见了,通过闭包Store Value从而实现accessor,适用于所有浏览器. 复制代码 代码如下: function Sandy(val){ var value = val; this.getValue = function(){ return value; }; this.setValue = function(val){ value = val; }; } //usage var sandy = new Sandy("test"); sandy.value // => undefined sandy.setValue("test2") sandy.getValue
下面是JavaScript权威指南(中文第五版)中P152页使用闭包的一个例子. 复制代码 代码如下: function makeProperty(o, name, predicate) { var value; //This is property value;
//The setter method simply returns the value o["get" + name] = function() { return value;};
//The getter method stores the value or throws an exception if //the predicate rejects the value o["set" + name] = function(v) { if (predicate && !predicate(v) { throw "set" + name + ": invalid value " + v; } else { value = y; } } }
//The following code demenstrates the makeProperty() method var o = {}; // Here is an empty object
//Add property accessor methods getName and setName //Ensure that only string values are allowed makeProperty(o, "Name", function(x) { return typeof x == "string"; });
o.setName("Frank"); //Set the property value; print(o.getName()); //Get the property value o.setName(0); //Try to set a value of the wrong type
第二种方法是使用__defineSetter__与__defineGetter__来实现accessor,看下划线就知道它们并非标准,适用于Firefox 2.0+, Safari 3.0+, Google Chrome 1.0+ 和 Opera 9.5+ ,方法使用见MDN. 复制代码 代码如下: function Sandy(val){ var value = val, _watch = function(newVal) { console.log("val is Changed to : " + newVal); }