[Javascript] Immute Object
2016-06-27 16:06
393 查看
Three ways to make object immutable:
1. Use JSON.parse(JSON.stringify(obj)): this approach is little bit expense.
2. Use Object.create()
This is a cheap way to do.
Because Object.create() actually doesn't do a deep copy of the original object, it jut create a pointer to the original object, we can verify by:
As we can see it is just a empty object.
3. Use Object.assign:
1. Use JSON.parse(JSON.stringify(obj)): this approach is little bit expense.
2. Use Object.create()
var person = { name: "Wan" } var copyPerson = Object.create(person); console.log(copyPerson.name); //Wan
This is a cheap way to do.
Because Object.create() actually doesn't do a deep copy of the original object, it jut create a pointer to the original object, we can verify by:
console.log(JSON.stringify(copyPerson)); //"{}"
As we can see it is just a empty object.
3. Use Object.assign:
var person = { name: "Wan" } var copyPerson = Object.assign({}, person); console.log(copyPerson.name); //"Wan" console.log(JSON.stringify(copyPerson)); //"{\"name\":\"Wan\"}"
相关文章推荐
- 【翻译+笔记】【高质量Objective-C-2】第1条:了解Objective-C语言的起源-Maoyingyong
- Objective-C Runtime整理(方法和消息)
- 【高质量Objective-C-1】目录结构-Effective Objective-C 2.0
- JSONKit does not support Objective-C Automatic Reference Counting(ARC) / ARC forbids Objective-C objects in struct
- 编程中如何避免if(object!=null)判空语句
- Objective-C用讯飞SDK实现语音识别
- ObjectOutputStream/ObjectInputStream
- [Effective JavaScript 笔记]第47条:绝不要在Object.prototype中增加可枚举的属性
- ObjectARX参考源码&文档
- Object.observe() js新特性
- Objective-C学习笔记-NSString
- Js判断参数(String,Array,Object)是否为undefined或者值为空
- 面向接口编程之提炼接口(Objective-C )
- Why doesn't Objective-C support private methods?
- Object-Oriented Analysis and Design Using UML 翻译与学习 (一)
- object-c
- Transform 、GameObject 区别【新手向】
- 文件空指针错误java.io.StreamCorruptedException: java.io.ObjectInputStream:NullPointerExpception
- Volley StringRequest和JSONObjectRequest使用几个细节
- Note On <You Don't Know JS - this and Object Prototypes>