Search code examples
javascriptprototypal-inheritance

Surrogate instance changing classes when creating prototypal inheritance?


So i'm trying to setup prototypal inheritance using the surrogate method and I have run into a behavior that seems weird for me. Here are my classes:

function Animal(name) { 
    this.name = name;
}

Animal.prototype.eat = function() { 
    console.log("mmm... food...")
};

function Dog(name) { 
    this.name = name 
};

var Surrogate = function() {}
Surrogate.prototype = Animal.prototype;

Now, I want to setup Animal as the base class. If I make an instance of Surrogate:

enter image description here

The browser console says that s is an instance of Surrogate.

However, when I set Dog class's prototype to the instance of Surrogate:

enter image description here

It becomes an instance of Animal? Why is this happening? Is this correct or am I interpreting it wrong?


Solution

  • using the surrogate method

    Protip: Use Object.create for this which has been standard for a decade now :-)

    It becomes an instance of Animal?

    No. It's still exactly the same object and no functionality changed. It's an instanceof Animal just like it had been before.

    The Animal {} you see in the console is a custom display choice of the debugger.

    Why is this happening?

    My guess would be that you see a side effect of an internal optimisation that occurs when an object is assigned as the .prototype of a function, which is observable in the debugger only.