我希望能够做一些像这样的事情
foo.x = 7;然后将该属性设置为只读,这样其他代码就不能更改它。我想要
foo.x = 10; //should do nothing什么都不做,在JS中有没有这样做呢?
发布于 2012-10-04 23:40:07
使用ECMAScript5,您可以实现这一点:
var foo = {};
Object.defineProperty(foo, 'x', {
value: 7,
writable: false,
configurable: false,
enumerable: true
});您可能需要查看MDN JavaScript中的ECMAScript5内容。
发布于 2012-10-04 23:37:30
我想this就是你要找的人。检查Writable attribute下的示例
不过,它只能在提供ECMA5支持的浏览器中工作。对于较老的浏览器,您不能定义一个不可写的属性,但您可以设置一个可与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...发布于 2012-10-04 23:43:39
您可以使用Object.defineProperty来完成此操作。
Object.defineProperty(foo, "x", {writable:false})
查看此Fiddle
如果要使整个对象不可写,还可以使用Objects freeze方法
Object.freeze(foo);
https://stackoverflow.com/questions/12730746
复制相似问题