admin管理员组文章数量:1400115
I'd like to be able to do something like
foo.x = 7;
And then do something to make that property read only so that no other code can change it. IE i'd like
foo.x = 10; //should do nothing
To do nothing is there anyway to do that in JS?
I'd like to be able to do something like
foo.x = 7;
And then do something to make that property read only so that no other code can change it. IE i'd like
foo.x = 10; //should do nothing
To do nothing is there anyway to do that in JS?
Share Improve this question asked Oct 4, 2012 at 15:34 asutherlandasutherland 2,9694 gold badges38 silver badges51 bronze badges 1- Check this out: stackoverflow./questions/2428409/… It might be helpful – MikeB Commented Oct 4, 2012 at 15:36
4 Answers
Reset to default 6With ECMAScript5 you can achieve that:
var foo = {};
Object.defineProperty(foo, 'x', {
value: 7,
writable: false,
configurable: false,
enumerable: true
});
You might want to check out MDN JavaScript for ECMAScript5 stuff.
I think this is what you're looking for. Check the example under Writable attribute
It only works in browsers that offer ECMA5 support, though. For older browsers, you can't define a non-writeable propery, but you can set a private variable which can be used with a getter:
var foo = (function(x)
{
var getX = function()
{
return x;
};
getX.valueOf = function()
{
return this();
};
return {x:x,getX:getX};
})(7);//pass constant value
foo.x === 7;//true
foo.x = 5;//will work
//BUT:
foo.getX();//returns 7, always
foo.getX;//returns 7, so can be used as though it weren't a method
//WARNING:
foo.getX = 213;//x is lost forever...
You can use Object.defineProperty to do this.
Object.defineProperty(foo, "x", {writable:false})
See this Fiddle
If you want to make an whole Object unwritable, you could also use the Objects freeze method
Object.freeze(foo);
Well, for backwards patibility with old browsers you may need to define accessor functions. Alternatively you can use ready-made functionality provided by various frameworks (e.g. 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.
- Tengiz
本文标签: Javascript Is there a way to make a object property read onlyStack Overflow
版权声明:本文标题:Javascript: Is there a way to make a object property read only - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744140128a2592581.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论