Gwa*_*r17 1 javascript class ecmascript-5
我的期望是我用新的toString方法覆盖了Vehicle的toString方法.然而,这似乎不起作用,我不知道为什么.基于这篇文章看起来应该是https://strongloop.com/strongblog/an-introduction-to-javascript-es6-classes/(向下滚动到Class Extending)
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
Run Code Online (Sandbox Code Playgroud)
作为第二个参数给出的属性对象Object.create应该包含属性描述符,而不仅仅是值.这纠正了问题:
Motorcycle.prototype = Object.create(Vehicle.prototype, {
toString: {
configurable: true, enumerable: true, writable: true,
value: function() {
return 'Motorcycle ' + this.make + ' ' + this.year;
}
}
});
Run Code Online (Sandbox Code Playgroud)
另请参阅MDN参考Object.create.