Javascript 模块中的常量或最终变量
我正在尝试编写一些代码,这些代码允许我根据我使用的变量名称检索整数值。但是,我试图使整数值成为最终值或无法更改的值。我在下面放置了一些代码,这些代码允许我检索上面解释的值。谁能告诉我如何使它们成为最终变量或其他什么?提前致谢。
(function() {
// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = {
RED: "#FF0000",
BLUE: "#0000FF",
GREEN: "#00FF00",
};
})();
alert(MyModule.RED); // #FF0000
I am trying to write some codes which allow me to retrieve integer values based on the variable name i use. however, i am trying to make the integer values a final value or something which can't be changed. i have placed some codes below which allows me to retrieve values as explain above. can anyone tell me how issit possible for me to make them a final variable or something? Thanks in advance.
(function() {
// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = {
RED: "#FF0000",
BLUE: "#0000FF",
GREEN: "#00FF00",
};
})();
alert(MyModule.RED); // #FF0000
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
免责声明:就安全性而言,常量/最终变量是愚蠢的。就性能的提高而言,因为 js 引擎可以对其进行更多优化,我怀疑它会产生影响。
基准测试显示性能没有明显提高。除了迂腐或伪安全之外,这实际上没有用。
唯一的用例是冻结库的一部分,这样用户就不会搬起石头砸自己的脚。
使用 ES5
Object.freeze
你可以(并且强烈推荐)使用ES5-shim升级旧版/旧版浏览器的合规性。
您也可以只使用
Object.defineProperties
使用
Object.create
小心将原型设置为
null
,您可能需要将其设置为Object.prototype< /代码>
Disclaimer: In terms of security constant / final variables are silly. In terms of increased performance because the js engine can optimise it more I doubt it makes a difference.
Benchmark shows no noticable increase in performance. This isn't actually useful apart from pedantry or pseudo security.
The only use case is making part of your library frozen so that users don't shoot themself in the foot.
With ES5
Object.freeze
You can (and it's highly recommended) use the ES5-shim to upgrade older/legacy browsers for compliance.
You can also just use
Object.defineProperties
There is a nice shortcut for the above using
Object.create
Be wary that sets the prototype to
null
, you may want to set it toObject.prototype
我知道做到这一点的最好/唯一的方法是将 RED、BLUE、GREEN 等声明为函数并返回一个常量值,如下所示:
有人仍然可以覆盖该函数来执行不同的操作,但从语义上来说更难做到- 函数看起来更像是不应该被覆盖。
The best/only way I know to do this is to declare RED, BLUE, GREEN, etc. as functions and return a constant value, like so:
Someone can still overwrite the function to do something different, but it's semantically more difficult to do - a function seems more so like it shouldn't be overwritten.
您可以创建一个只读属性(即具有
getter
但没有setter
的属性)。如果使用 ECMAScript5,请查看
Object.defineProperty()
。一些早期版本支持
object.__defineGetter__()
。You can create a read-only property (i.e. one that has a
getter
but nosetter
).If using ECMAScript5 check out
Object.defineProperty()
.Some earlier versions support
object.__defineGetter__()
.