Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对象文本内的继承_Javascript_Oop_Inheritance_Javascript Objects_Prototype Chain - Fatal编程技术网

Javascript 对象文本内的继承

Javascript 对象文本内的继承,javascript,oop,inheritance,javascript-objects,prototype-chain,Javascript,Oop,Inheritance,Javascript Objects,Prototype Chain,所以我也有这类汽车和汽车选装件,我希望新包装的对象奥迪继承汽车和汽车选装件类的权利。可以在对象文本中继承属性和方法吗 可以在对象文本中继承属性和方法吗 目前还没有,但使用ES6,这将是可能的: function Car(model, color, power){ this.model = model; this.color = color; this.power = power; this.is_working = true; this.sound =

所以我也有这类汽车和汽车选装件,我希望新包装的对象奥迪继承汽车和汽车选装件类的权利。可以在对象文本中继承属性和方法吗

可以在对象文本中继承属性和方法吗

目前还没有,但使用ES6,这将是可能的:

 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);
其中
bar
成为
foo
的原型

然而,我认为你的意思是,是否有可能用特定的原型创建对象。您可以使用:

var foo = {
    __proto__: bar
};
或者,如果已有对象,则可以使用:

但是,在您的特定情况下,将
Audi
的原型设置为任何东西都没有价值,因为
Car
Car\u optionals
没有在其
原型
对象上定义任何东西。所有内容都设置在函数本身中,因此您只需将这些函数应用于
Audi

foo.setPrototypeOf(bar);
更自然的方法是通过
Car
创建一个新实例:

Car.call(Audi, 'A4', 'blue', 180);
Car_optionals.call(Audi);
call()函数会帮我解决这个问题。这就是我要找的。谢谢!
Car.call(Audi, 'A4', 'blue', 180);
Car_optionals.call(Audi);
var Audi = new Car('A4', 'blue', 180);
Car_optionals.call(Audi);