Search code examples
javascriptoopconstructorobject-literal

can a literal object inherit from class?


So I was thinking if a literal object can inherit properties and methods from a class. Here is the code

var Foo = function(val1, val2) {
    this.prop1 = val1;
    this.prop2 = val2;
}

var bar = {
    //how to inherit properties from Foo class; also add new property
    prop3: 'val3'
};

Solution

  • You could achieve this by creating an instance of Foo and then adding properties to that instance like so:

    var Foo = function(val1, val2) {
        this.prop1 = val1;
        this.prop2 = val2;
    }
    
    var x = new Foo('valOfProp1', 'valOfProp2');
    
    x.prop3 = 'valOfAddedProp';