【问题标题】:JavaScript Prototype Inheritance did not workJavaScript 原型继承不起作用
【发布时间】:2018-09-29 02:44:07
【问题描述】:

我有一个名为 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”。 谁能解释一下为什么我的继承不起作用?

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

    您正在混合继承模式。您的继承不起作用,因为model 不在superCar 原型链上,它直接在对象本身上。

    您可以将superCar 做成一个类似car 的函数并将其绑定到继承链中,如下所示:

    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 的原型链接:

    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);

    您也许可以混合使用这两种模式,但这会让人感到困惑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多