码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Immute Object

时间:2016-06-27 17:28:29      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

Three ways to make object immutable:

 

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\"}"

 

[Javascript] Immute Object

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5620476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!