silent_coder
silent_coder

Reputation: 6502

How to inherit STATIC methods?

I have a class

function Man(){...}

Man.drinkBeer = function(){...}

I need to inherit SuperMan from Man. And I still want my Superman be able to drink some beer.

How can I do that?

Upvotes: 5

Views: 119

Answers (2)

Naftali
Naftali

Reputation: 146302

This is what CoffeeScript does for class inheritance:

var __hasProp = {}.hasOwnProperty,
    __extends = function (child, parent) {
        for (var key in parent) {
            if (__hasProp.call(parent, key)) child[key] = parent[key];
        }
        function ctor() {
            this.constructor = child;
        }
        ctor.prototype = parent.prototype;
        child.prototype = new ctor();
        child.__super__ = parent.prototype;
        return child;
    };

And they use it like so:

var Man = (function(){
    function Man() { ... }
    ...
    return Man;
})();
....
var SuperMan = (function(_super){
    __extends(SuperMan, _super);
    function SuperMan() { ... }
    ...
    return SuperMan;
})(Man);
....

Upvotes: 2

SLaks
SLaks

Reputation: 887285

Object.setPrototypeOf(SuperMan, Man);

This will set the internal __proto__ property of your derived function to be the base function.
Therefore, the derived function will inherit all properties from the base function.

Note that this affects the functions themselves, not their prototypes.

Yes, it's confusing.

No existing browser supports setPrototypeOf(); instead, you can use the non-standard (but working) alternative:

SuperMan.__proto__ = Man;

Upvotes: 6

Related Questions