const obj1 = {test: "Hello"};
const obj2 = obj1;
obj2 is not the copy of obj1, but it is obj1 too. in javascript
objects are mutable, they are addressed by reference, not by value.
console.log(obj1) //{ test: 'Hello' }
console.log(obj2) //{ test: 'Hello' }
obj1.test = "Hello Obj1";
console.log(obj1) //{ test: 'Hello Obj1' }
console.log(obj2) //{ test: 'Hello Obj1' }
Another case
const obj1 = {test: "Hello"};
const obj2 = Object.create(obj1);
console.log(obj1) //{ test: 'Hello' }
console.log(obj2) //{}
console.log(obj2.test) // Hello
When you create an object using the Object.create then its values
become proto to the created object
obj1.test = "Hello Obj1";
console.log(obj1) //{ test: 'Hello Obj1' }
console.log(obj2) //{}
console.log(obj2.test) // Hello Obj1
obj2.test = "Hello Obj2";
console.log(obj1) //{ test: 'Hello Obj1' }
console.log(obj2) //{ test: 'Hello Obj2' }
console.log(obj2.__proto__) //{ test: 'Hello Obj1' }
It creates a new property for the test but still the prototype value
refer to obj1
Top comments (0)