2

我正在尝试使从此类继承成为可能:

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 

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

4

2 回答 2

4

除了@elclanrs 所说的:

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

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

于 2013-05-17T02:42:17.823 回答
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);

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

于 2013-05-17T02:39:04.883 回答