2016-08-14 69 views
1

我正在学习JavaScript继承。我发现了一个很好的解释在这里: JavaScript Inheritance不理解Javascript继承

function A() { 
    B.call(this); 
} 

function B() { 
    C.call(this); 
    this.bbb = function() { 
     console.log("i was inherited from b!"); 
    } 
} 

我想基于以上和其他的解决方案来实现继承(有一群人在网上,他们都似乎表明不同的东西)。无论如何,我试图让SportsCar继承Car并使用汽车的describeSelf方法。我不确定我做错了什么。 PLUNK for convenience

var Car = function(make, topSpeed, color){ 
    this.make = make; 
    this.topSpeed = topSpeed; 
    this.color = color; 
} 

Car.prototype.describeSelf = function(){ 
    document.write('Hi, I am a: ' + this.make + ', my top speed is ' + this.topSpeed + ' and I am ' + this.color); 
} 

var corolla = new Car('toyota', 120, 'blue'); 

corolla.describeSelf(); 

//Code works fine up to here 
var SportsCar = function(engineSize, make, topSpeed, color) { 
    Car.call(this, make, topSpeed, color); 
    this.engineSize = engineSize; 
}; 

var fordGt = new SportsCar('V8', 'ford', 205 , 'red'); 

fordGt.describeSelf(); 

我真不明白什么call一样。

编辑:看起来我不清楚我在问什么。问题的实质是让这条线路工作:fordGt.describeSelf();并得到我目前做错了什么的解释。

+0

@JaromandaX我欣赏这​​个链接,但是这并没有帮助我理解如何向子对象的构造函数添加新属性MDN上的示例不会传递新的道具 – VSO

+0

我的问题是如何使继承正常工作,例如如何使这条线工作:fordGt.describeSe如果();我会更新这个问题。 – VSO

+0

你绝对没有在SportCar的原型链中设置Car'SportCar.prototype = Object.create(Car);'。 –

回答

1

添加行注释add this

var Car = function(make, topSpeed, color){ 
    this.make = make; 
    this.topSpeed = topSpeed; 
    this.color = color; 
} 

Car.prototype.describeSelf = function(){ 
    document.write('Hi, I am a: ' + this.make + ', my top speed is ' +  this.topSpeed + ' and I am ' + this.color); 
} 

var corolla = new Car('toyota', 120, 'blue'); 

corolla.describeSelf(); 

//Code works fine up to here 
var SportsCar = function(engineSize, make, topSpeed, color) { 
    Car.call(this, make, topSpeed, color); 
    this.engineSize = engineSize; 
}; 

// add this 
SportsCar.prototype = Object.create(Car.prototype); 

var fordGt = new SportsCar('V8', 'ford', 205 , 'red'); 

fordGt.describeSelf(); 

这是因为您确实需要正确设置原型链,以便新创建的对象在链中具有其父原型。

如果,在另一方面,附加方法链可以忽略不计(因为你已经从其他构造函数调用构造函数对象本身

var Car = function(make, topSpeed, color){ 
    this.make = make; 
    this.topSpeed = topSpeed; 
    this.color = color; 
    this.describeSelf = function() ... 
} 

,但是你会落得多个实例附加到新创建的实例相同的功能

+0

谢谢,这有很大的帮助。 – VSO