Difference between freeze and seal in Javascript

2019-01-16 01:24发布

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?

7条回答
仙女界的扛把子
2楼-- · 2019-01-16 02:21

Object.freeze() creates a frozen object, which means it takes an existing object and essentially calls Object.seal() on it, but it also marks all “data accessor” properties as writable:false, so that their values cannot be changed. - Kyle Simpson, You Don't Know JS - This & Object Prototypes

查看更多
登录 后发表回答