JavaScript中的Get和Set访问器
时间:2010-09-18 来源:梦想
前两天IE9 Beta版发布了,对于从事WEB开发的朋友们来说真是个好消息啊,希望将来有一天各个浏览器都能遵循统一的标准。今天要和大家分享的是JavaScript中的Get和Set访问器,这个是在看一个本地存储的例子的时候发现的,原来早在Javascript1.5中就已经支持了的,只是有些浏览器没有很好的实现。看到的例子的代码如下:
function Note(){
var _text="just for test";
}
Note.prototype = {
get text()
{
return this._text;
},
set text(x)
{
this._text = x;
}
}
var note = new Note();
note.text="a new note";
var noteStr=note.text // return "a new note"
在如下浏览器能正常工作:
我们常用的实现方法可能是这样的:
function Field(val){
var value = val;
this.getValue = function(){
return value;
};
this.setValue = function(val){
value = val;
};
}
var field = new Field("test");
field.setValue("test2")
field.getValue() // return "test2"
在DOM元素上Get和Set访问器的实现
HTMLElement.prototype.__defineGetter__("description", function () {
return this.desc;
});
HTMLElement.prototype.__defineSetter__("description", function (val) {
this.desc = val;
});
document.body.description = "Beautiful body";
// document.body.description will now return "Beautiful body";
在如下浏览器能正常工作:
通过Object.defineProperty实现访问器
将来ECMAScript标准的扩展对象的方法会通过Object.defineProperty来实现,这也是为什么IE8就是通过这种方法来实现get和set访问器,看来微软还是很有远见的,遗憾的是目前只有IE8+和Chrome 5.0+支持,其它的浏览器都不支持,而且IE8+也只支持DOM元素,不过将来的版本将和Chrome一样支持普通的Javascript对象。
IE8+支持DOM元素上的Get和Set访问器的实现
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"
在如下浏览器能正常工作:
Chrome 5.0+支持普通对象的Get和Set访问器的实现
var lost = {
loc : "Island"
};
Object.defineProperty(lost, "location", {
get : function () {
return this.loc;
},
set : function (val) {
this.loc = val;
}
});
lost.location = "Another island";
// lost.location will now return "Another island"
在如下浏览器能正常工作:
总结
尽管微软的IE只是支持了Object.defineProperty,没有完美的实现Get和Set访问器,但是我们已经看到了IE有了很大的进步,特别是刚发布的IE9使用的新的javascript引擎,支持HTML5和CSS3,支持硬件加速等等,相信有一天各个浏览器都能完全拥抱标准,带来一个完美的WEB世界。










