OOP JS

by mpetrovich

JavaScript

function subclass(o) {
    function f() {};
    f.prototype = o.prototype;
    return new f();
}

/* Parent class */

function Parent(foo) {
    console.log("[Parent constructor]");
    this.foo = foo;
}

Parent.prototype.bar = function() {
    console.log("Parent.bar() " + this.foo);
};
    
Parent.prototype.parent = function() {
    console.log("parent()");
};

/* Child class */

function Child(foo) {
    console.log("[Child constructor]");
    Child.prototype.parent.constructor.apply(this, arguments);
}
    
Child.prototype = subclass(Parent);
Child.prototype.constructor = Child;
Child.prototype.parent = Parent.prototype;
    
Child.prototype.bar = function() {
    console.log("Child.bar() " + this.foo);
    Child.prototype.parent.bar.apply(this, arguments);
};
    
Child.prototype.child = function() {
    console.log("child()");
};
    
/* Usage */
console.log("==================================");

console.log("[New child]");
var c = new Child("Bob");
c.bar();
c.child();
console.log("c instanceof Child =", c instanceof Child);
console.log("c instanceof Parent =", c instanceof Parent);
console.log("");

console.log("[New parent]");
var p = new Parent("Jim");
p.bar();
p.parent();
console.log("p instanceof Child =", p instanceof Child);
console.log("p instanceof Parent =", p instanceof Parent);
console.log("");

console.log(p);