user3234209
user3234209

Reputation: 995

Python like inheritance for JavaScript

In python I can do something like this

main.py

class MainClass:
    def __init__(self):
        self.name = "some_name"
    def startDoingStuff(self):
        print("I'm doing something boring")

    def printName(self):
        print("My name is " + self.name)

sub.py

import main
class Sub(main.MainClass):
    def startDoingStuff(self):
        print("I'm doing something interesting")
        self.name = "sub"

sub = Sub()
sub.printName() # prints 'My name is some_name'
sub.startDoingStuff()
sub.printName() # prints 'My name is sub'

Is there a JavaScript equivalent?

Upvotes: 2

Views: 150

Answers (1)

Retsam
Retsam

Reputation: 33439

If prototype-based inheritance is a little daunting, you might look into extension based inheritance.

A really basic implementation looks like this. (John Resig's implementation linked above is more robust, but I think this is a little more readable, but with the same basic concept)

var extend = function(subTypeInit) {
    var SuperType = this;
    var SubType = function () {
         function SuperTypeProxy(args) {
              return SuperType.apply(this, args);
         }
         var base = new SuperTypeProxy(arguments);
         subTypeInit.apply(base, arguments);
         return base;
    }
    SubType.extend = extend.bind(SubType);
    return SubType;
}

Then it can be used like this:

var Main = function (name) {
    var self = this;
    self.name = name;
    self.doSomething = function () {
         console.log("something boring");
    };
    self.printName = function () {
         console.log("Hi, I'm "+name);
    };
};

Main.extend = extend.bind(Main); //Manually attach to first parent.

var Sub = Main.extend(function () {
    var self = this;

    self.doSomething = function () {
         console.log("something interesting");
    };

    var superPrintName = self.printName;
    self.printName = function () {
         superPrintName();
         console.log("And I'm a sub class");
    };
});

var sub = new Sub("foo");
sub.doSomething(); //logs "something interesting"
sub.printName(); //logs "Hi, I'm foo" "And I'm a sub class"

Some caveats here, you really probably should look into prototype based inheritance, which is what javascript is really built for. Extension-based inheritance is a little more natural for someone who's used to other OO languages' approaches to inheritance, but the disadvantage is that it consumes more resources to do inheritance this way; you're creating a lot of functions (and a lot of closures), which can really add up.

Upvotes: 2

Related Questions