Search code examples
javascriptclassecmascript-5

second argument Object.create


My expectation was that I'd overwrite Vehicle's toString method with a new toString method. However this doesn't seem to work and I don't know why. Based on this article it looks like it should https://strongloop.com/strongblog/an-introduction-to-javascript-es6-classes/ (scroll down to 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

Solution

  • The properties object given as the second argument of Object.create is supposed to contain property descriptors, not just values. This corrects the issue:

    Motorcycle.prototype = Object.create(Vehicle.prototype, {
      toString: {
        configurable: true, enumerable: true, writable: true, 
        value: function() {
          return 'Motorcycle ' + this.make + ' ' + this.year;
        }
      }
    });
    

    See also the MDN reference for Object.create.