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?
I’ll show you how I achieve this sort of thing:-
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.callas a base class constructor. This avoids the duplication you have in the original.As to avoiding
newit 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:-Although I see little gain here.