第二个参数Object.create

时间:2017-05-22 22:37:50

标签: javascript class ecmascript-5

我的期望是我用新的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

2 个答案:

答案 0 :(得分:5)

作为Object.create的第二个参数给出的属性对象应该包含属性描述符,而不仅仅是值。这纠正了问题:

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

答案 1 :(得分:0)

要覆盖此方法,请首先将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());