在JavaScript中定义只读属性 [英] Defining read-only properties in JavaScript
问题描述
给定一个对象 obj
,我想定义一个只读属性'prop'
并设置它值为 val
。这是正确的方法吗?
Given an object obj
, I would like to define a read-only property 'prop'
and set its value to val
. Is this the proper way to do that?
Object.defineProperty( obj, 'prop', {
get: function () {
return val;
}
});
结果应该是(对于 val ='test'
):
obj.prop; // 'test'
obj.prop = 'changed';
obj.prop; // still 'test' since it's read-only
此方法适用于btw:http://jsfiddle.net/GHMjN/
我只是不确定这是否是最简单/最顺利/最合适的方式这样做...
This method works btw: http://jsfiddle.net/GHMjN/
I'm just unsure if this is the easiest / smoothest / most proper way to do it...
推荐答案
您可以使用可写
属性属性描述符,它可以防止需要 get
访问者:
You could instead use the writable
property of the property descriptor, which prevents the need for a get
accessor:
var obj = {};
Object.defineProperty(obj, "prop", {
value: "test",
writable: false
});
如评论中所述,可写
选项默认为 false
所以你可以在这种情况下省略它:
As mentioned in the comments, the writable
option defaults to false
so you can omit it in this case:
Object.defineProperty(obj, "prop", {
value: "test"
});
这是ECMAScript 5所以不适用于旧浏览器。
This is ECMAScript 5 so won't work in older browsers.
这篇关于在JavaScript中定义只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!