2

What are the differences between the 2 following approaches for inheritance?

Subclass.prototype = $.extend(true, {}, Parent.prototype, proto);

and

function Subclass(){
    var parent = new Parent();
    $.extend(true, this, parent);
}

Pros and cons of each approach?

Thanks!

EDIT: I'm currently using the 1st approach to extend my classes, but I'm thinking of instantiating a parent object instead, so that the constructor of the Parent class gets called. Although I'm not convinced I'd always want that...

Alex Heyd
  • 1,323
  • 1
  • 10
  • 17
  • Where does this line occur: `$.extend(true, this, parent);`? It matters where this is called because the value of `this` is context-dependent. Is this in the global scope? – Wayne Apr 05 '11 at 17:13
  • ah sorry, it'd be called in the class' constructor, I'll edit the post – Alex Heyd Apr 05 '11 at 19:07

1 Answers1

3

The major difference is in the second example, new Parent(), you are actually calling Parent and creating a new object which could cause unintended problems.

Using $.extend with the prototype like the first example, no code is going to be run. jQuery will look at the prototypes and extend the object for you and there won't be the possible side effects of running Parent()

There is no way I can explain it as well as this guy who has the top answer: How to "properly" create a custom object in JavaScript?

Here is a quote from the linked answer

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

Community
  • 1
  • 1
Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
  • thanks for the link. Yeah, the reason I was thinking about this was because I thought there might be cases I'd want to the run the Parent's constructor function (setting up instance level properties for example) but I think I'll stick to the first (current) approach I'm using – Alex Heyd Apr 05 '11 at 19:40