冻结和密封之间的区别 [英] Difference between freeze and seal

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

问题描述

我刚刚听说过JavaScript方法 freeze 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"

freeze 印章?它们可以提高性能吗?

What is the difference between freeze and seal? Can they increase performance?

推荐答案

Object.seal


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

  • 这将使每个现有属性不可配置:它们无法从数据描述符转换为访问描述符(反之亦然)反之亦然),并且访问描述符的属性完全不能修改(而数据描述符可以更改其 writable 属性和其 value 属性(如果 writeable 为真)。

  • 可以引发 TypeError 尝试修改密封对象本身的值时(最常见于 strict模式

  • 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)

< a href = https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze rel = noreferrer> Object.freeze


  • Object.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)

测试:密封的对象冻结的对象

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

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