JavaScript Object.freeze冻结对象

Object.freeze是干嘛用的呢?看看API解释的

Prevents the modification of existing property attributes and values, and prevents the addition of new properties.

就是说把一个对象freeze之后就不能修改存在的属性和值了,就是key value都不能修改,而且也不能添加新的属性

// Create an object that has two properties.  
var obj = { name: "Nicholas", length: 10 }

// Freeze the object.  
Object.freeze(obj)

// Try to add a new property, and then verify that it is not added.   
obj.newProp = 50

console.log(obj.newProp) // Ouput: undefined

以上就是要添加一个属性,虽然没有脚本错误提示,但是不成功

// Create an object that has two properties.  
var obj = { name: "Nicholas", length: 10 }

// Freeze the object.  
Object.freeze(obj)

obj.name = 'Jan'

console.log(obj.name) // Ouput: Nicholas

要修改原有的值,也不成功

并且,StackOverflow上有人说:

There is no way to do this, once an object has been frozen there is no way to unfreeze it.

意思是只要freeze之后,就不能解除了,所以使用这个API需要谨慎

分享

TITLE: JavaScript Object.freeze冻结对象

LINK: https://www.qttc.net/186-javascript-object-freeze.html

NOTE: 原创内容,转载请注明出自琼台博客