我有一个名为 superCar 的对象。我有一辆功能车。我想从 superCar 对象继承我的汽车对象。这是我的代码:
var superCar = {
model : "sedan"
};
function Car(){
this.name = null;
}
var c1 = new Car();
c1.name="Toyota";
var c2 = new Car();
c2.name="Bmw";
console.log(c1.name);
console.log(c2.name);
c1.__proto__.__proto__ = superCar.__proto__ ;
console.log(c1.model);
我预计输出将是“Toyota”、“Bmw”、“sedan”。但输出为“Toyota”、“Bmw”、“undefined”。 你们中的任何人都可以解释一下为什么我的继承不起作用吗?
最佳答案
您正在混合继承模式。您的继承不起作用,因为 model
不在 superCar
原型(prototype)链上,它直接位于对象本身上。
您可以使 superCar
成为一个像 car 一样的函数,并将其绑定(bind)到继承链中,如下所示:
function superCar(){
this.model = "sedan"
};
function Car(){
superCar.call(this) // this will add model and other properties assigned in the constructor
this.name = null;
}
Car.prototype = Object.create(superCar.prototype); // this will add protoype methods from superCar, but there aren't any
var c1 = new Car();
c1.name="Toyota";
var c2 = new Car();
c2.name="Bmw";
console.log(c1.name);
console.log(c2.name);
console.log(c1.model);
console.log(c2.model);
或者,您可以使用 Object.create
创建一个到 对象 superCar
的原型(prototype)链接,其中包含基于此的内容:
let superCar ={
model: "sedan"
};
function Car(name){
let obj = Object.create(superCar) // obj will delegate to superCar when it doesn't find a property
obj.name = name
return obj
}
var c1 = Car("Toyota");
var c2 = Car("Bmw");
console.log(c1.name);
console.log(c2.name);
console.log(c1.model);
console.log(c2.model);
您也许可以混合使用这两种模式,但这会令人困惑。
关于JavaScript 原型(prototype)继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564629/