我正在尝试使从此类继承成为可能:
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
有人可以向我解释有什么问题吗?我想这不是实现它的写入方式,但为什么呢?