第二个参数 Object.create



我的期望是我会用一个新的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;
    }
  }
});

另请参阅 MDN 参考 Object.create

若要重写该方法,请首先将 Motorcycle 的原型构造函数指向自身。 请阅读以下代码中的注释

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); //Motorcycle.prototype is an object that inherits from Vehicle.prototype
// and is still pointing to the Vehicle constructor 
Motorcycle.prototype.constructor = Motorcycle; // changing the constructor back to Motorcycle;
// method overridden after Motorcycle is pointing its own constructor
// now override the toString method
Motorcycle.prototype.toString=function(){
console.log("inside the motorcycle toString ")
}
var motorcycle = new Motorcycle('harley', 2010);
console.log(motorcycle.toString()); 

最新更新