在 JavaScript 中定义只读属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7757337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Defining read-only properties in JavaScript
提问by ?ime Vidas
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 obj
,我想定义一个只读属性'prop'
并将其值设置为val
。这是正确的方法吗?
Object.defineProperty( obj, 'prop', {
get: function () {
return val;
}
});
The result should be (for val = 'test'
):
结果应该是(对于val = 'test'
):
obj.prop; // 'test'
obj.prop = 'changed';
obj.prop; // still 'test' since it's read-only
This method works btw: http://jsfiddle.net/GHMjN/
I'm just unsure if this is the easiest / smoothest / most proper way to do it...
顺便说一句,此方法有效:http: //jsfiddle.net/GHMjN/
我只是不确定这是否是最简单/最流畅/最合适的方法...
回答by Tim Down
You could instead use the writable
property of the property descriptor, which prevents the need for a get
accessor:
您可以改为使用writable
属性描述符的属性,这样就不需要get
访问器了:
var obj = {};
Object.defineProperty(obj, "prop", {
value: "test",
writable: false
});
As mentioned in the comments, the writable
option defaults to false
so you can omit it in this case:
如评论中所述,该writable
选项默认为,false
因此在这种情况下您可以省略它:
Object.defineProperty(obj, "prop", {
value: "test"
});
This is ECMAScript 5 so won't work in older browsers.
这是 ECMAScript 5,所以不能在旧浏览器中工作。
回答by Firanolfind
In new browsers or node.jsit is possible to use Proxyto create read-only object.
在新的浏览器或node.js 中,可以使用Proxy创建只读对象。
var obj = {
prop: 'test'
}
obj = new Proxy(obj ,{
setProperty: function(target, key, value){
if(target.hasOwnProperty(key))
return target[key];
return target[key] = value;
},
get: function(target, key){
return target[key];
},
set: function(target, key, value){
return this.setProperty(target, key, value);
},
defineProperty: function (target, key, desc) {
return this.setProperty(target, key, desc.value);
},
deleteProperty: function(target, key) {
return false;
}
});
You can still assign new properties to that object, and they would be read-only as well.
您仍然可以为该对象分配新属性,并且它们也是只读的。
Example
例子
obj.prop
// > 'test'
obj.prop = 'changed';
obj.prop
// > 'test'
// New value
obj.myValue = 'foo';
obj.myValue = 'bar';
obj.myValue
// > 'foo'
回答by Tengiz
Because of the old browsers (backwards compatibility) I had to come up with accessor functions for properties. I made it part of bob.js:
由于旧的浏览器(向后兼容性),我不得不为属性提出访问器函数。我把它作为bob.js 的一部分:
var obj = { };
//declare read-only property.
bob.prop.namedProp(obj, 'name', 'Bob', true);
//declare read-write property.
bob.prop.namedProp(obj, 'age', 1);
//get values of properties.
console.log(bob.string.formatString('{0} is {1} years old.', obj.get_name(), obj.get_age()));
//set value of read-write property.
obj.set_age(2);
console.log(bob.string.formatString('Now {0} is {1} years old.', obj.get_name(), obj.get_age()));
//cannot set read-only property of obj. Next line would throw an error.
// obj.set_name('Rob');
//Output:
//========
// Bob is 1 years old.
// Now Bob is 2 years old.
I hope it helps.
我希望它有帮助。