JavaScript - 如何使继承成为可能

时间:2013-05-17 02:36:55

标签: javascript oop inheritance

我正试图从这个类继承:

function Vehicle(p) {
  this.brand = p.brand || "";
    this.model = p.model || "";
    this.wheels = p.wheels || 0;
}

Vehicle.prototype.getBrand = function () {
    return this.brand;
};
Vehicle.prototype.getModel = function () {
    return this.model;
};
Vehicle.prototype.getWheels = function () {
    return this.wheels;
};

var myVehicle = new Vehicle({
    brand: "Mazda",
    model: "RX7",
    wheels: 4
});

console.log(myVehicle);

我试过这样做:

function Vehicle(p) {
    this.brand = p.brand || "";
    this.model = p.model || "";
    this.wheels = p.wheels || 0;
}

Vehicle.prototype.getBrand = function () {
    return this.brand;
};
Vehicle.prototype.getModel = function () {
    return this.model;
};
Vehicle.prototype.getWheels = function () {
    return this.wheels;
};

function Car (){}
Car.prototype = new Vehicle();
Car.prototype.getWheels = function() {
    return 4;
};

var myCar = new Car({
    brand: "Mazda",
    model: "RX7"
});

console.log(myCar);

但似乎不起作用:

> Uncaught TypeError: Cannot read property 'brand' of undefined 

有人可以向我解释有什么问题吗?我想这不是实现它的写方式,但为什么呢?

2 个答案:

答案 0 :(得分:4)

除了@elclanrs所说的:

function Car () {
    Vehicle.apply(this, arguments);
}
var c = function() {};
c.prototype = Vehicle.prototype;
Car.prototype = new c();

现场演示:http://jsfiddle.net/x3K9b/1/

答案 1 :(得分:3)

您需要在Car中调用“超级”:

function Car() {
  Vehicle.apply(this, arguments);
}

除此之外,您可以通过仅指定一个空对象来使p成为可选项;这将摆脱错误。最后指向正确的构造函数:

function Vehicle(p) {
  p = p || {}; //<=
  this.brand = p.brand || "";
  this.model = p.model || "";
  this.wheels = p.wheels || 0;
}

//...

Car.prototype = new Vehicle();
Car.prototype.constructor = Car; //<=

修改:否则只需使用Object.create

Car.prototype = Object.create(Vehicle.prototype);

负责分配构造函数和所有内容。