javascriptoopobject-composition

Why does Object.assign add to the prototype's constructor?


I am learning composition in Javascript and was wondering why Object.assign() in my code is adding methods to the prototype's constructor rather than the object's constructor. I will link the code below. Basically, the code is adding two methods (eat and walk) to the Person object by using Object.assign(). But, as the image below shows, the console is displaying the methods as belonging to the Person.prototype's constructor rather than the Person object itself. I must be overthinking it. Any help is appreciated. Thanks!

enter image description here


enter image description here


Code

const canEat = {
    eat() {
        this.hunger--;
        console.log('eating');
    }
};

const canWalk = {
    walk: function() {
        console.log('walking');
    }
};

const canSwim = {
    swim: function() {
        console.log("swim");
    }
};

function Person() {

}

Object.assign(Person,canEat,canWalk);
const person = new Person();
console.log(person);


Solution

  • When Object.assign is evaluated:

    Object.assign(Person, canEat, canWalk);
    

    eat and walk properties are assigned to Person function.

    When the instance of Person is created:

    const person = new Person();
    

    Then we have a new object which has a constructor property pointed to the Person function. However the new object has neither eat nor walk properties (those belong to Person [constructor] function).

    If you want to make eat and walk properties available for instances of Person, you should assign those methods to Person.prototype instead:

    Object.assign(Person.prototype, canEat, canWalk);
    

    Because when an object is created with new operator, it inherits not from the constructor function Person, but from constructor function prototype Person.prototype.