我的期望是用新的 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
的第二个参数给出的属性对象应该包含属性描述符,而不仅仅是值。这更正了问题:
Motorcycle.prototype = Object.create(Vehicle.prototype, {
toString: {
configurable: true, enumerable: true, writable: true,
value: function() {
return 'Motorcycle ' + this.make + ' ' + this.year;
}
}
});
关于javascript - 第二个参数 Object.create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123138/