Search code examples
javascriptoopprototypal-inheritance

Getting the prototype of a constructor in javascript


I was reading about the new keyword in javascript on MDN and came across this line:

When a function is called with new, the constructor's prototype property will become the resulting object's prototype.

However, the code below didn't behave as I would expect. I assumed that Car.prototype would return the Car's prototype object. But it seems to just return an empty object. What am I missing here?

function Car(make, model, year) {
  this.make = make,
  this.model = model,
  this.year = year,
  this.started = false,
  this.start = function () {
     this.started = true;
  }),
  this.stop = function () {
      this.started = false;
  });
}
let corolla = new Car("Toyota", "Corolla", 2016);
console.log(Object.getPrototypeOf(corolla)); //{}
console.log(Car.prototype); //{}

Solution

  • You are absolutely correct. However, the prototype is an empty object because you never assign any properties to it. (instead, you assign properties to the newly created object itself.)

    Instead of assigning to this.start and this.stop from within the constructor function body, you'd have to assign to Car.prototype.start and Car.prototype.stop outside of the constructor function (below).

    function Car(make, model, year) {
      this.make = make;
      this.model = model;
      this.year = year;
      this.started = false;
    }
    Car.prototype.start = function () {
       this.started = true;
    };
    Car.prototype.stop = function () {
        this.started = false;
    };
    
    let corolla = new Car("Toyota", "Corolla", 2016);
    console.log(Object.getPrototypeOf(corolla));
    console.log(Car.prototype);