- 时间:2021-05-19 10:33 编辑: 来源: 阅读:
- 扫一扫,手机访问
摘要:JavaScript Accessor实现说明
第一种算是比较常见了,通过闭包Store Value从而实现accessor,适用于所有浏览器.
[url=https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object]MDN[/url].
[url=http://blogs.msdn.com/b/ie/archive/2009/01/13/responding-to-change-updated-getter-setter-syntax-in-ie8-rc-1.aspx]IEBlog[/url],该方法的使用见[url=https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty]MDN[/url].
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的文档. ^ ^
微信版

扫一扫进微信版
返回顶部