有没有办法制作“Object.frozen”尝试更改对象时会抛出警告吗?
我使用 Object.freeze 作为防止自己违反自己规则的一种手段。当我尝试做一个糟糕的作业时,我希望 Object.freeze 能够跟我说话。然而,Object.freeze 只是让分配默默地失败!例如,如果我这样做,
/*
* Frozen singleton object "foo".
*/
var foo = (function() {
var me = {};
me.bar = 1;
if (Object.freeze) {
Object.freeze(me);
}
return me;
})();
foo.bar = 2;
console.log(foo.bar);
控制台将记录“1”,但我不会知道我曾经做过错误的分配。当冻结对象的全部目的是为了避免意外情况时,这当然可能会导致我的代码中出现危险的意外行为。事实上,我更有可能通过不冻结对象、让错误的分配发生以及让我的代码稍后由于错误的值而失败而获得详细的错误输出。
我想知道 JavaScript 是否在任何浏览器中都有隐藏的“不可变对象警告”编译指示,以便我可以知道何时尝试改变“Object.frozen”对象。
I use Object.freeze as a means to prevent myself from breaking my own rules. I would like Object.freeze to speak to me when I try to make a bad assignment. However, Object.freeze simply makes the assignments silently fail! For example, if I do
/*
* Frozen singleton object "foo".
*/
var foo = (function() {
var me = {};
me.bar = 1;
if (Object.freeze) {
Object.freeze(me);
}
return me;
})();
foo.bar = 2;
console.log(foo.bar);
the console will log "1", but I won't know that I ever made a bad assignment. This of course can lead to dangerous unexpected behavior in my code, when the whole point of freezing the object was to avoid the unexpected. In fact, I'm more likely to get verbose error output by not freezing the object, letting the bad assignment take place, and having my code fail later on because of the bad value.
I'm wondering if JavaScript has any hidden "immutable object warning" pragma in any browser, so that I can know when I attempt to mutate an "Object.frozen" object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
严格模式下的代码在尝试分配给不可写属性时将抛出
TypeError
(ECMA-262:11.13.1)。但请注意,您不能依赖不完全支持 ES5 严格模式的浏览器(例如 IE9)中抛出的错误。要使代码在严格模式下运行,请在包含该代码的 JS 文件或函数的开头添加
'use strict';
,并在实现严格模式的环境中运行它(例如,请参见此列表) :http://caniuse.com/#feat=use-strict)。Code in strict mode will throw a
TypeError
when trying to assign to an unwritable property (ECMA-262: 11.13.1). But do notice you cannot rely on the error being thrown in browsers that don't fully support ES5 strict mode (such as IE9).To make your code run in strict mode, add
'use strict';
at the beginning of the JS file or function containing the code and run it in an environment that implements strict mode (see for example this list: http://caniuse.com/#feat=use-strict).接受的答案对我不起作用。我将其放入答案中是因为我无法在评论中清楚地格式化它。
从 Chrome 109 的控制台:
The accepted answer isn't working for me. I'm putting this in an answer because I couldn't format it clearly in a comment.
From console in Chrome 109: