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?

1
  • Surrogate is an instance of Animal, so it follows that Dog should also be an instance of Animal to the debugger Commented Jan 6, 2021 at 17:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.