Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make an "Object.frozen" object throw warnings when an attempt is made to change it?

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.

like image 764
Milosz Avatar asked Feb 02 '12 20:02

Milosz


1 Answers

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

like image 69
Felix Loether Avatar answered Sep 20 '22 15:09

Felix Loether