简体   繁体   中英

Inheritance within object literals

 function Car(model, color, power){
    this.model = model;
    this.color = color;
    this.power = power;
    this.is_working = true;
    this.sound = function(){
        console.log("Vrummm!");
    };
}
 function Car_optionals(){
     this.turbo_boost = true;
     this.extra_horsepower = 20;
     this.name_tag = "Badass";
 }

Car.prototype = new Car_optionals();
var Audi = {};
Audi.prototype = new Car();
console.log(Audi.is_working);

So i'm having this too classes Car and Car_optionals and I want the newly crated object Audi to inherit proprietyes from both Car and Car_optionals classes. It is posible to inherit proprietyes and methods within object literals?

It is posible to inherit proprietyes and methods within object literals?

Not yet, but with ES6, this will be possible:

var foo = {
    __proto__: bar
};

where bar becomes the prototype of foo .

However, I rather think you mean whether it's possible to create objects with a specific prototype. You can use Object.create for that:

var foo = Object.create(bar);

Or if you have an already existing object, you can use Object.setPrototypeOf :

foo.setPrototypeOf(bar);

In your specific case though, there is no value in setting the prototype of Audi to anything, because Car and Car_optionals don't define anything on their prototype objects. Everything is set inside the functions itself, so you simply have to apply those functions to Audi :

Car.call(Audi, 'A4', 'blue', 180);
Car_optionals.call(Audi);

And the more natural way would be to create a new instance through Car :

var Audi = new Car('A4', 'blue', 180);
Car_optionals.call(Audi);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM