有没有办法阻止替换JavaScript对象属性? [英] Is there any way to prevent replacement of JavaScript object properties?
问题描述
我想使对象的结构不可变,防止其属性随后被替换。但是,属性需要是可读的。这可能吗?
I would like to make an object's structure immutable, preventing its properties from being subsequently replaced. The properties need to be readable, however. Is this possible?
我确信没有语言功能(在Java中没有 final
) C#中的 readonly
支持这一点,但想知道是否有其他机制可以实现相同的结果?
I'm sure there are no language features (along the lines of final
in Java and readonly
in C#) to support this but wondered whether there might be another mechanism for achieving the same result?
I我正在寻找这些方面的东西:
I'm looking for something along these lines:
var o = {
a: "a",
f: function () {
return "b";
}
};
var p = o.a; // OK
o.a = "b"; // Error
var q = o.f(); // OK
o.f = function () { // Error
return "c";
};
推荐答案
ECMAScript 5将有印章()
和 freeze()
,但是使用当前的JavaScript实现没有好办法。
ECMAScript 5 will have seal()
and freeze()
, but there's no good way to do this with current JavaScript implementations.
来源。
这篇关于有没有办法阻止替换JavaScript对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!