DEV Community

loading...

Object.create, basic understandings

Khan M. Tabish
Full stack JS developer, React, NodeJS, MongoDB
Updated on ・1 min read

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

Discussion (0)