inheritance

by migerh

JavaScript

var extend = function (base, sub, ext) {
            var i;
            
            function SurrogateCtor() {}

            SurrogateCtor.prototype = base.prototype;
            sub.prototype = new SurrogateCtor();
            sub.prototype.constructor = sub;

            // Add a reference to the parent's prototype
            sub.base = base.prototype;

            // Copy the methods passed in to the prototype
            for (i in ext) {
                if (ext.hasOwnProperty(i)) {
                    sub.prototype[i] = ext[i];
                }
            }

            // We want to be able to define the constructor inline
            return sub;
        };


var Base = function Base() {
    this.bar = 'foo';
};

var Value = function Value() {
    this.foo = 'bar';
};
extend(Base, Value, {});

var v = new Value();
alert(Value.base.constructor.name);
alert(v instanceof Base);
//alert(v.hasOwnProperty('foo'));
//alert(v.hasOwnProperty('bar'));