Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Difference between freeze and 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 freeze and seal? Can they increase performance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object.seal

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

Object.freeze

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

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.


Performance:

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

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

Tests: Sealed objects, Frozen objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...