0

I have a pretty good understanding of JavaScript's prototypal inheritance but I wouldn't say it's perfect. I am looking at the latest prototypal syntax for JavaScript inheritance and so far it makes pretty good sense.

__proto__ is used for looking up parent function's prototype. Say I have Cat and Mammal, I can simply point Cat.prototype.__proto__ to Mammal.prototype.

ChildClass.prototype.__proto__ = ParentClass.prototype;
ChildClass.prototype.constructor = ChildClass;

The use of __proto__ was strongly discouraged because it was not standardized only until recently. Thus, the modern standardized practice is to use Object.create

ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;

Now let's look at ES5's surrogate approach

function Surrogate() {};
Surrogate.prototype = ParentClass.prototype;
ChildClass.prototype = new Surrogate();
ChildClass.prototype.constructor = ChildClass;

Obviously,

ChildClass.prototype = ParentClass.prototype;

is bad, because modifying ChildClass's prototype will also modify ParentClass's prototype.

But why can't we do this?

ChildClass.prototype = new ParentClass();

Why do we need a surrogate in between?

mofury
  • 644
  • 1
  • 11
  • 23
  • 2
    Personally I'd say your `ES5's surrogate approach` isn't entirely accurate. `Object.create` was added in `5.1` in 2011 so it's been around an extremely long time as far as modern JS goes. – loganfsmyth Sep 05 '17 at 20:43
  • `new` was used *before* ES5 introduced `Object.create`. – Bergi Sep 05 '17 at 21:12

1 Answers1

1

But why can't we do this?

ChildClass.prototype = new ParentClass();

How do you know that calling ParentClass constructor w/o arguments would not throw an error?

Imagine ParentClass was implemented this way.

function ParentClass(name) {
  if(!name) throw new Error('name is required');

  this.name = name;
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Ahhh thank you, good point! Is that the only reason for doing surrogate class? Is there any other hidden caveat I should be aware of and that surrogate trick is designed to catch? – mofury Sep 05 '17 at 19:23
  • @cfeng Any other side effect `ParentClass` could do. For example it might call external API, increment counter etc. – Yury Tarabanko Sep 05 '17 at 19:34
  • 1
    @cfeng We just don't want to call the constructor at all. What should it initialise? There's no instance around. – Bergi Sep 05 '17 at 21:13