Last Updated: February 20, 2016
·
858
· tonsky

Direct javascript inheritance

Implementation:

var _with = function(proto, overrides) {
    if (!overrides) overrides = {};

    // that's the trick
    var ctor = function() { this.__proto__ = proto; };
    ctor.prototype = proto;
    var child = new ctor();
    // 'child'.[[Prototype]] pseudoproperty is set to 'proto' now
    // and real 'child.__proto__' property added

    for (var prop in overrides)
        if (overrides.hasOwnProperty(prop))
            child[prop] = overrides[prop];
    return child;
};

Usage example:

var Clazz = { 
    x: 10, 
    y: 20, 
    method: function() {
        return this.x;
    },
    method2: function() {
        return this.__proto__.x; // referencing parent
    }
};
var DerivedClazz = _with(Clazz, {x: 15});

var instance = _with(DerivedClazz);
alert(instance.y);         // 20
instance.x = 100;
alert(instance.x);         // 100
alert(instance.method());  // 100
alert(instance.method2()); // 15
alert(DerivedClazz.x);     // 15
alert(Clazz.x);            // 10

As described here: http://tonsky.livejournal.com/244260.html

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside