当冻结对象发生变异时,Object.freeze不会在严格模式下抛出异常

时间:2017-10-08 22:45:50

标签: javascript

在严格模式下使用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。

这是预期的行为还是我做错了什么?

1 个答案:

答案 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();




希望这有帮助! :)

相关问题