Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading