Javascript中冻结和密封的区别 [英] Difference between freeze and seal in Javascript

查看:205
本文介绍了Javascript中冻结和密封的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚听说过JavaScript方法冻结 seal ,它们可用于使任何对象不可变。

I just heard about the JavaScript methods freeze and seal, which can be used to make any Object immutable.

以下是如何使用它的简短示例:

Here's a short example how to use it:

var o1 = {}, o2 = {};
Object.freeze(o2);

o1["a"] = "worked";
o2["a"] = "worked";

alert(o1["a"]);   //prints "worked"
alert(o2["a"]);   //prints "undefined"

这些方法之间的区别是什么?它们能否提高性能?

What is the difference between these methods and can they increase performance?

推荐答案

Object.seal


  • 它可以防止从密封对象中添加和/或删除属性;使用 delete 将返回false

  • 它会使每个现有属性不可配置:它们无法从数据描述符转换为访问者描述符(和反之亦然),并且根本不能修改访问者描述符的属性(而数据描述符可以更改其可写属性,以及他们的属性,如果可写为真)。

  • 可以抛出 TypeError 尝试修改密封对象本身的值时(最常见的是严格模式

  • It prevents adding and/or removing properties from the sealed object; using delete will return false
  • It makes every existing property non-configurable: they cannot be converted from 'data descriptors' to 'accessor descriptors' (and vice versa), and no attribute of accessor descriptors can be modified at all (whereas data descriptors can change their writable attribute, and their value attribute if writeable is true).
  • Can throw a TypeError when attempting to modify the value of the sealed object itself (most commonly in strict mode)

对象.freeze


  • 究竟是什么 O bject.seal 确实,加上:

  • 它阻止修改任何现有属性

  • Exactly what Object.seal does, plus:
  • It prevents modifying any existing properties

两者都不会影响'深'/孙子对象。例如,如果冻结 obj ,则无法重新分配 obj.el ,但<$ c $的值c> obj.el 可以修改,例如 obj.el.id 可以更改。

Neither one affects 'deep'/grandchildren objects. E.g., if obj is frozen, obj.el can’t be reassigned, but the value of obj.el could be modified, e.g. obj.el.id can be changed.

根据浏览器的不同,封闭或冻结对象可能会影响其枚举速度:

Sealing or freezing an object may affect its enumeration speed, depending on the browser:


  • Firefox:枚举性能不受影响

  • IE:枚举性能影响微不足道

  • Chrome:密封或冻结对象的枚举性能更快

  • Safari:密封或冻结对象的枚举速度减慢92%(截至2014年)

  • Firefox: enumeration performance is not impacted
  • IE: enumeration performance impact is negligible
  • Chrome: enumeration performance is faster with sealed or frozen objects
  • Safari: sealed or frozen objects enumerate 92% slower (as of 2014)

测试:密封对象冻结对象

这篇关于Javascript中冻结和密封的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆