0

In C#, inheritance is as easy as:

class Animal {
    string name;

    public Animal() { }
}

class Dog : Animal {
    public Dog() : base() {
        this.name = "Dog";
    }
}

In node.js, I want to have two files (animal.js and dog.js) replicate the above setup while being as simple and non-hacky as possible.

Is this even possible with node.js? If it matters, I'd like to do all this so that I can pass the Animal type through a function without checking the subclass as there will be dozens of classes inheriting the Animal class.

Scott
  • 41
  • 4
  • possible duplicate of [JavaScript Inheritance](http://stackoverflow.com/questions/7486825/javascript-inheritance) – spender Oct 16 '14 at 10:42
  • You could look into writing your NodeJS apps via [TypeScript](http://www.typescriptlang.org/) if you're a C# fanboy. – Marty Oct 16 '14 at 10:46
  • https://www.google.com/search?q=javascript+inheritance+site%3Astackoverflow.com – spender Oct 16 '14 at 10:47
  • 1
    @Marty: TypeScript looks amazing, please post that as an answer and I'll mark it. – Scott Oct 16 '14 at 10:52
  • Typescript tries to follow ecma 6 which will be class based. It has good tooling as well (better than most js toolls ) if you want to know about JavaScript prototype maybe this answer can help. http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 it isn't that hard to understand once you wrap your head around it – HMR Oct 16 '14 at 13:24

1 Answers1

1

I wanted to mark Marty for the answer but it doesn't look like he's going to. I tried out TypeScript and it was exactly what I wanted, I didn't have to deal with all the inheritance headaches that plague Javascript (prototyping, etc.)

Just as a pro-tip to anyone that finds this answer, don't forget to grab the type definitions for middleware when using TypeScript. You can find them here. Don't forget to add the references into your .ts files (for example: ///<reference path='node/node.d.ts' />).

Scott
  • 41
  • 4
  • Prototypes are not a headache, the are the fundamental basic for inheritance. Your typescript does use them as well. – Bergi Oct 16 '14 at 13:22
  • @Scott Yeh, it's definitely worth taking at least a peek at the generated code. IIRC, the typescript way translates to quite a lot of boilerplate in the longhand javascript. TypeScript is pretty rocking though... roll on generators and better support for Promises. You might also enjoy taking a peek at google's (experimental) traceur project. You can bootstrap the compiler directly in your own page which eliminates the need for pre-compilation. https://github.com/google/traceur-compiler/wiki/LanguageFeatures#classes – spender Oct 16 '14 at 13:56
  • I'm glad you invested enough time even to find the definitions for existing libraries :-) – Marty Oct 16 '14 at 20:17