简体   繁体   中英

Proper inheritance for node.js

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM