DEV Community

Khan M. Tabish
Khan M. Tabish

Posted on • Edited on

Object.create, basic understandings

Alt Text

    const obj1 = {test: "Hello"};
    const obj2 = obj1; 
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

Another case

    const obj1 = {test: "Hello"};
    const obj2 = Object.create(obj1);
    console.log(obj1) //{ test: 'Hello' }
    console.log(obj2) //{}
    console.log(obj2.test) // Hello
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

It creates a new property for the test but still the prototype value
refer to obj1

Top comments (0)