2014-04-25 50 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 
*/