Javascript 对象文本内的继承
所以我也有这类汽车和汽车选装件,我希望新包装的对象奥迪继承汽车和汽车选装件类的权利。可以在对象文本中继承属性和方法吗 可以在对象文本中继承属性和方法吗 目前还没有,但使用ES6,这将是可能的: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 =
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);