2

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?

raffayatiq
  • 159
  • 9
  • Surrogate is an instance of Animal, so it follows that Dog should also be an instance of Animal to the debugger – AGE Jan 06 '21 at 17:36

1 Answers1

1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375