Semi simple JS class/object/prototype inheritance

With the least code?

by rudiedirkx

JavaScript

// This is it?
Object.prototype.parent = function(method, arg1) {
    var args = [].slice.call(arguments, 1);
    return this.constructor.prototype[method].apply(this, args);
};
Object.prototype.extend = function(sup, methods) {
    if ( sup) {
        this.prototype = Object.create(sup.prototype);
        this.prototype._parent = sup;
    }
    if ( methods ) {
        for ( var m in methods ) {
            if ( methods.hasOwnProperty(m) ) {
                this.prototype[m] = methods[m];
            }
        }
    }
};

// And to illustrate:
function Person(name) {
    console.log('constructing Person (from ' + get_class(this) + ' / ', this , ')');
    this.name = name || Math.random();
}
Person.extend(null, {
    talk: function(what) {
        what || (what = 'nothing');
        return 'Person [' + this.name + '] says ' + what;
    },
    dance: function() {
        return 'Person dancing here!';
    }
});

p = new Person('P1');

function Ninja(name) {
    console.log('constructing Ninja (from ' + get_class(this) + ' / ', this , ')');
    Person.call(this, name);
}
Ninja.extend(Person, {
    fight: function() {
        return 'I KILL you!';
    },
    talk: function(what) {
        return 'Ninja says ' + this.parent('talk', what);
    }
});

n = new Ninja('N1');

function Ronin(name) {
    console.log('constructing Ronin (from ' + get_class(this) + ' / ', this , ')');
    Ninja.call(this, name);
}
Ronin.extend(Ninja, {
    dance: function() {
        return 'Is there a ' + this.parent('dance') + '?';
    }
});

r = new Ronin('R1');

console.log(p.talk('PERSON HERE')); // "Person [P1] says PERSON HERE"
console.log(n.talk('NINJA HERE')); // "Ninja says Person [N1] says NINJA HERE"
console.log(r.dance()); // "Is there a Person dancing here!?"


// Stupid jsFiddle scope
window.Person = Person;
window.Ninja = Ninja;
window.Ronin = Ronin;


function get_class(obj) {
//console.log(obj.__proto__.constructor);
    var C = String(obj.__proto__.constructor);
    return...