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.

5
  • possible duplicate of JavaScript Inheritance Commented Oct 16, 2014 at 10:42
  • You could look into writing your NodeJS apps via TypeScript if you're a C# fanboy. Commented Oct 16, 2014 at 10:46
  • google.com/… Commented Oct 16, 2014 at 10:47
  • 1
    @Marty: TypeScript looks amazing, please post that as an answer and I'll mark it. Commented Oct 16, 2014 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. stackoverflow.com/questions/16063394/… it isn't that hard to understand once you wrap your head around it Commented Oct 16, 2014 at 13:24

1 Answer 1

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' />).

Sign up to request clarification or add additional context in comments.

3 Comments

Prototypes are not a headache, the are the fundamental basic for inheritance. Your typescript does use them as well.
@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. github.com/google/traceur-compiler/wiki/…
I'm glad you invested enough time even to find the definitions for existing libraries :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.