有没有办法制作“Object.frozen"?尝试更改对象时抛出警告?

2022-01-11 00:00:00 object console warnings javascript

我使用 Object.freeze 来防止自己违反自己的规则.当我尝试做一个糟糕的任务时,我希望 Object.freeze 能和我说话.然而, Object.freeze 只是让分配默默地失败!例如,如果我这样做

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);

控制台会记录1",但我不知道我曾经做过错误的分配.这当然会导致我的代码中出现危险的意外行为,而冻结对象的全部目的是为了避免意外.事实上,我更有可能通过不冻结对象、让错误的分配发生以及让我的代码稍后因为错误的值而失败来获得详细的错误输出.

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.

我想知道 JavaScript 在任何浏览器中是否有任何隐藏的不可变对象警告"编译指示,以便我可以知道何时尝试对Object.frozen"对象进行变异.

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.

推荐答案

严格模式下的代码在尝试分配给不可写属性时会抛出 TypeError (ECMA-262: 11.13.1).但请注意,您不能依赖在不完全支持 ES5 严格模式(例如 IE9)的浏览器中引发的错误.

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).

要让你的代码在严格模式下运行,请在包含代码的 JS 文件或函数开头添加 'use strict'; 并在实现严格模式的环境中运行(参见例如此列表:http://caniuse.com/#feat=use-strict).

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).

相关文章