Search code examples
javascriptobjectinheritanceprototypegetter-setter

Why does the getter/setter methods get inherited as a property in child object?


I was exploring the Object.create() method and came across something interesting. When I passed an Object with a getter method in it (made using get keyword), the getter method was implicitly present in the new Object alongside the Prototype object and also inside the Prototype object.

Why is it that a get method becomes a property in the new object because as per my understanding, the Object.create() method will simply create an empty object and put the passed argument as the new Object's prototype.

Here's my code :

let obj = {
    fname: "hello",
    lname: "world",
    get getName() {
        return `${this.fname} ${this.lname}`;
    },
};

let newObj = Object.create(obj);
console.log(newObj);

And here's what it displays on the browser console :- Console Image displaying the newObj

I tried accessing the getName method on the newObj and it printed "hello world". I am not sure if this is because of prototype chaining or is it because the newObj has getName as its property.

Please let me know whats happening in the context of Object Literals and not in case of Classes.


Solution

  • the getter method was implicitly present in the new object:

    No it is not present in the object. It's only the console trying to be helpful by displaying it there, which admittedly is very confusing. The purpose is so that by clicking on the "(...)" you can run the getter on that object, where it might access the particular object's state (via this), unlike what happens if you were to access it on the prototype object.

    You can verify it doesn't become an own property of the new object:

    const proto = {
        fname: "hello",
        lname: "world",
        get fullName() {
            return `${this.fname} ${this.lname}`;
        },
    };
    
    const obj = Object.create(proto);
    obj.fname = "hi";
    console.log(obj.hasOwnProperty("fullName"));
    console.log(obj);

    Notice that the "inherited getter" is displayed in a slightly different (not bold) font than an own property of the object:

    log result of obj with own fname and expanded proto