【问题标题】:Inheritance within object literals对象字面量内的继承
【发布时间】:2015-03-12 21:43:57
【问题描述】:
 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);

所以我也有这个类 Car 和 Car_optionals,我希望新创建的对象 Audi 继承 Car 和 Car_optionals 类的属性。可以在对象字面量中继承属性和方法吗?

【问题讨论】:

    标签: javascript oop inheritance javascript-objects prototype-chain


    【解决方案1】:

    可以在对象字面量中继承属性和方法吗?

    还没有,但是有了 ES6,这将是可能的:

    var foo = {
        __proto__: bar
    };
    

    其中bar 成为foo 的原型。

    但是,我认为您的意思是是否可以创建具有特定原型的对象。您可以为此使用Object.create

    var foo = Object.create(bar);
    

    或者如果你有一个已经存在的对象,你可以使用Object.setPrototypeOf:

    foo.setPrototypeOf(bar);
    

    但在您的具体情况下,将Audi 的原型设置为任何值都没有任何价值,因为CarCar_optionals 没有在它们的prototype 对象上定义任何内容。一切都在函数内部设置,因此您只需将这些函数应用于Audi

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

    更自然的方式是通过Car创建一个新实例:

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

    【讨论】:

    • 那么 call() 函数会为我解决问题。这就是我要找的。谢谢!
    猜你喜欢
    • 2013-02-22
    • 2014-02-23
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多