JavaScript Accessor實現說明

來源:互聯網
上載者:User

第一種算是比較常見了,通過閉包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的文檔. ^ ^

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.