Search code examples
javascriptprototypejavascript-objects

Js - prototypal inheritance with object create function


I am wondering why in this piece of code, when I am trying to access the properties of the object that the garfield is made of, in this case Cat, I am getting undefined:

function Cat(){
    this.legs = 2;
    this.species = 'cat';
};

Cat.prototype.makeSound = function() {
    console.log(this.sound); // logs undefined 
};

const garfield = Object.create(Cat);
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) // logs undefined 

Shouldn't I be able to get down the prototype inheritance chain the access to those properties?


Solution

  • The word OOP contains "object" in its definition; meaning that you are dealing with objects.

    Javascript does something special that it exposes the objects directly, in which you can use them without abstractions (without classes).

    To create an object, you can just declare it with {}. no need to create a class to get one like in java for example.

    To use Inheritance directly, you need to have an object, and append things to its prototype.

    Here is an example:

    const Cat = {
      legs: 2,
      species: 'cat',
    };
    
    Object.setPrototypeOf(Cat, {
      makeSound() {
        console.log(this.sound); // logs undefined 
      }
    })
    
    
    const garfield = Object.create(Cat);
    garfield.sound = 'feed me';
    garfield.makeSound();
    console.log(garfield.legs) //2

    To use Inheritance using functions, you'd have to construct the function first to get the object out of the function (the this) and the prototype will automatically be appended to the this object.

    function Cat(){
        this.legs = 2;
        this.species = 'cat';
    };
    
    Cat.prototype.makeSound = function() {
        console.log(this.sound); // logs undefined 
    };
    
    const garfield = new Cat();
    garfield.sound = 'feed me';
    garfield.makeSound();
    console.log(garfield.legs) // 2