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\"}"
时间: 2024-11-07 12:57:52