Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript multilevel inheritance

I've been trying to get my head around JavaScript inheritance. Confusingly, there seem to be many different approaches - Crockford presents quite a few of those, but can't quite grok his prose (or perhaps just fail to relate it to my particular scenario).

Here's an example of what I have so far:

// base class
var Item = function( type, name ) {
    this.type = type;
    this.name = name; // unused
};

// actual class (one of many related alternatives)
var Book = function( title, author ) {
    this.name = title; // redundant (base class)
    this.author = author;
};
Book.prototype = new Item('book'); // duplication of "book"

// instances
var book = new Book('Hello World', 'A. Noob');

This approach leaves me with a fair amount of redundancy, as I cannot delegate instance-specific attributes to the base class (at the time of prototype assignment, the attribute value is unknown). Thus each subclass has to repeat that attribute. Is there a recommended way to solve this?

Bonus question: Is there a reasonable way to avoid the "new" operator, or would that be regarded as a newbie working against the language?

like image 898
evanb Avatar asked Feb 06 '10 12:02

evanb


1 Answers

I'll show you how I achieve this sort of thing:-

 function Item(type, name)
 {
    if (arguments.length > 0)
    {
        this.type = type;
        this.name = name;
    }
 }

 function Book(title, author)
 {
   Item.call(this, "book", title);
   this.author = author;
 }
 Book.prototype = new Item();

So a couple of things I'm doing here, I skip some initialisation code in the base class when I detect a new instance is being created simply as prototype.

The real enabler that avoids your duplication is to use Item.call as a base class constructor. This avoids the duplication you have in the original.

As to avoiding new it would help if you indicate why you would want to? However a simple way is to add a function to the "Class function" directly rather than to the prototype of the function:-

Book.Create = function (title, author) { return new Book(title, author); }


var aBook = Book.Create("Code Complete 2", "Steve McConnell");

Although I see little gain here.

like image 135
AnthonyWJones Avatar answered Oct 03 '22 02:10

AnthonyWJones