問題描述
我使用 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"?嘗試更改對象時拋出警告?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!