Search code examples
javascriptjqueryoopinheritanceprototypal-inheritance

Use $.extend() for prototypal inheritance?


Maybe this is a crazy question, but something like:

var MyPrototypeObject {
    prop: 0;
};    
var ob1 = Object.create(MyPrototypeObject);
var ob2 = { 
    meth: function() { 
        this.prop = 5; // update prop 
        return this.prop;
    }
};

where Object.create clones the prototype and $.extend is used to add additional methods to ob1, where this.prop points back to the prototype? What's the best way to add new methods?

$.extend(ob1, ob2);

Related: Override Methods with Prototypal Inheritance.


Solution

  • pd-style is similar and recommends

    var SomeProto = {
        prop: 0;
    };    
    
    var ob1 = extend(Object.create(SomeProto), { 
        meth: function meth() { 
            return (this.prop = 5); // update prop 
        }
    });
    

    This is an effective way of handling OO in JavaScript. Note that $.extend is a shit implementation for doing this because it has an isPlainObject check which returns false for objects that have prototypes