在严格模式下使用Object.freeze()
时,当我尝试修改冻结对象的属性时,它不会抛出异常。
MDN says将抛出TypeError
:
在严格模式下,此类尝试将抛出TypeErrors
以下是一些简单的代码:
'use strict';
//jshint esnext:true
const func = () => {
const o = { id: 0 };
Object.freeze(o);
o.id = 3;
};
func();
演示: https://jsbin.com/fobokipive/edit?js,console
代码不会抛出任何TypeError
。我正在使用基于Chromium的Opera。
这是预期的行为还是我做错了什么?
答案 0 :(得分:3)
你正确地做到了;问题似乎与JSBin有关。 通过JSFiddle( as seen here )运行完全相同的代码会引发错误:
未捕获的TypeError:无法分配给只读属性' id'对象#'
在StackSnippet中运行它也会产生同样的错误:
'use strict';
//jshint esnext:true
const func = () => {
const o = { id: 0 };
Object.freeze(o);
o.id = 3;
};
func();

此错误仅在严格模式下抛出:
//jshint esnext:true
const func = () => {
const o = { id: 0 };
Object.freeze(o);
o.id = 3;
};
func();

希望这有帮助! :)