2014-04-25 76 views
0

我嘗試在Javascript中行使繼承性。 eCar從繼承自Vehicle的汽車繼承。但似乎我不能使用帶Car或eCar對象的方法「getInfo()」。 如果我在瀏覽器中執行這樣的結果是:。我是否繼承了對象的方法?我怎樣才能達到結果?

Manufacture: Siemens 

undefined 
undefined 

請告訴我我在尋找的是:

Manufacture: Siemens 
Manufacture: VW 
Manufacture: Tesla 

function Vehicle(herst){ 

    this.manuf = herst; 
} 

Vehicle.prototype.getInfo = function(){ 
    return 'Manufacture: '+ this.manuf+'<br>'; 
} 


Car.prototype = Vehicle; 
Car.prototype.construtor = Vehicle; 
Car.prototype.getInfo = Vehicle; 


function Car(){ } 

eCar.prototype = Car; 
eCar.prototype.construtor = Car; 
eCar.prototype.getInfo = Car; 

function eCar(){ } 


Train = new Vehicle('Siemens'); 
document.write(Train.getInfo()+"<br>"); 


Golf = new Car('VW'); 
document.write(Golf.getInfo()+"<br>"); 


Tesla = new eCar('Tesla'); 
document.write(Tesla.getInfo()+"<br>"); 
+1

我建議看看[簡介面向對象的JavaScript(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript)。它提供了一個關於如何設置繼承的例子。 –

+0

我認爲它是'Car.prototype = new Vehicle();'和'eCar.prototype = new Car();'等等不是嗎? – Andy

+1

@最好不要,你正在創建一個Vehicle實例來設置Car的原型。車輛具有特定於實例的成員,它們現在處於Car的共享原型上,並且可能會有意想不到的結果。您可以通過在Car構造函數中使用'Vehicle.call(this,args)'來調解,但在定義對象時創建Vehicle的實例時仍然會遇到麻煩。更好地使用Object.create和polyfil它爲舊版瀏覽器 – HMR

回答

1

你很親密,只是一些事情需要不同。

// Vehicle 
function Vehicle(herst){ 
    this.manuf = herst; 
} 
Vehicle.prototype.getInfo = function() { 
    return 'Manufacture: '+ this.manuf+'<br>'; // you really want to return HTML? 
}; 
Vehicle.prototype.construtor = Vehicle; 

// Car 
function Car(){ 
    Vehicle.apply(this, arguments); // extends Vehicle 
} 
Car.prototype = Object.create(Vehicle.prototype); // inherits Vehicle's prototype 
Car.prototype.construtor = Car; 

// eCar 
function eCar(){ // constructors usually start with a capital 
    Car.apply(this, arguments); // extends Car 
} 
eCar.prototype = Object.create(Car.prototype); 
eCar.prototype.construtor = eCar; 

// use it 

var Train = new Vehicle('Siemens'), // variables usually start lower case 
    Golf = new Car('VW'), 
    Tesla = new eCar('Tesla'); 

我選擇Object.create成立繼承,有些人使用的Bar.prototype = new Foo()格式喜歡,但我覺得這調用在錯誤的時間構造Foo


這是什麼樣子?

var foo = new eCar('Foo'); 
foo instanceof eCar; // foo has eCar's prototype 
         // eCar was used to construct foo 
foo instanceof Car;  // foo inherited Car's prototype via eCar's prototype 
         // at the beginning of eCar, Car was applied to foo 
foo instanceof Vehicle; // foo inherited Vehicle's prototype via Car's prototype 
         // at the beginning of Car, Vehicle was applied to foo 
/* 
    So `foo` has own properties as assigned by Vehicle, then Car, then eCar, 
    and it has the prototype from eCar which shadows the prototype from Car 
    which again shadows the prototype from Vehicle 
*/