Subclasses with Vanilla JS

by rpflorence

JavaScript

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var merge = function(obj1, obj2){
    for (attrname in obj1) { obj2[attrname] = obj1[attrname]; }
    return obj2;
};

var math = Object.create({
    init: function(x, y){
        this.x = x;
        this.y = y;
        return this;
    },
    
    sum: function(){
        return this.x + this.y;
    }
});

var math2 = Object.create(merge(math,{
    
    product: function(){
        return this.x * this.y;
    }
    
}));

var sum1 = math.init(2,3).sum();
var sum2 = math2.init(10,20).sum();
var product = math2.product();

console.log(sum1, sum2, product);