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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…