第一種算是比較常見了,通過閉包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);
}
this.__defineGetter__("value", function(){
return value;
});
this.__defineSetter__("value", function(val){
value = val;
_watch(val);
});
}
var sandy = new Sandy("test");
sandy.value
// => test
sandy.value = "test2";
// => 'val is Changed to : test2'
sandy.value
// => "test2"
除了__defineG/Setter__外, 你還可以使用'set'、'get'關鍵字在在原型對象上定義accessor,對於單個對象同樣適用, 適用於Firefox 2.0+, Safari 3.0+, Google Chrome 1.0+ 和 Opera 9.5+.
復制代碼 代碼如下:
function Sandy(val){
this.value = val;
}
Sandy.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
//Or
var sandy = {
'_value' : 'sandy',
get value() {
return this._value;
},
set value(val) {
this._value = val;
}
}
最後一種方法,用到了Object的靜態方法defineProperty,作用於單個對象,該方法應該屬於ES5的范疇了,目前
似乎只有Chrome 支持這種方法,其實Ie8也支持,但操作對象僅限於Dom節點(Dom node),見IEBlog,該方法的使用見MDN.
復制代碼 代碼如下:
var sandy = {}, rValue;
Object.defineProperty(sandy, 'value' ,
{
'set' : function(val) {
rValue = val;
},
'get' : function() {
return rValue;
},
'enumerable' : true,
'configurable' : true
}
)
//Ie8+
Object.defineProperty(document.body, "description", {
get : function () {
return this.desc;
},
set : function (val) {
this.desc = val;
}
});
document.body.description = "Content container";
// document.body.description will now return "Content container"
‘enumerable','configuralbe' 屬於ES5規范中的Property Attributes(屬性特性),在這裡就不做討論了,有興趣的Google或者直接去看ES5的文檔. ^ ^