Search code examples
javascriptinheritanceobject-literal

Achieve inheritance using object literal in JavaScript


How do i achieve this :

function Vehicle(){
    this.mobility = true;
};
function Car(){};
Car.prototype = new Vehicle();
var myCar = new Car();
console.log(myCar.mobility);

Using objects created with Object literals ?

I know about Object.create() but is there any way like

Car.prototype = new Vehicle();

to achieve that ?


Solution

  • Here's how you do it using __proto__:

    var propertiesToInherit = { 'horsepower': 201, 'make': 'Acura' }
    var myCar = {};
    myCar.__proto__ = propertiesToInherit;
    
    console.log(myCar.horsepower); // 201
    console.log(myCar.make); // Acura
    

    That being said, I would avoid doing this. It looks like it is deprecated