有没有一种方法可以使“ Object.frozen”成为可能。尝试更改对象时会抛出警告? [英] Is there a way to make an "Object.frozen" object throw warnings when an attempt is made to change it?

查看:98
本文介绍了有没有一种方法可以使“ Object.frozen”成为可能。尝试更改对象时会抛出警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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).

这篇关于有没有一种方法可以使“ Object.frozen”成为可能。尝试更改对象时会抛出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆