我的期望是我将使用新的toString方法覆盖Vehicle的toString方法。但是,这似乎不起作用,我也不知道为什么。根据本文看来,它应该https://strongloop.com/strongblog/an-introduction-to-javascript-es6-classes/(向下滚动至类扩展)
function Vehicle(make, year) {
this.make = make;
this.year = year;
}
Vehicle.prototype.toString = function() {
return this.make + ' ' + this.year;
};
var vehicle = new Vehicle('Toyota Corolla', 2009);
function Motorcycle(make, year) {
Vehicle.apply(this, [make, year]);
}
Motorcycle.prototype = Object.create(Vehicle.prototype, {
toString: function() {
return 'Motorcycle ' + this.make + ' ' + this.year;
}
});
Motorcycle.prototype.constructor = Motorcycle;
var motorcycle = new Motorcycle('harley', 2010);
console.log(motorcycle.toString()); //TypeError
最佳答案
作为Object.create
的第二个参数给出的properties对象应该包含属性描述符,而不仅仅是值。这可以解决问题:
Motorcycle.prototype = Object.create(Vehicle.prototype, {
toString: {
configurable: true, enumerable: true, writable: true,
value: function() {
return 'Motorcycle ' + this.make + ' ' + this.year;
}
}
});
另请参见MDN reference for
Object.create
。