🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Prototypes

A prototype is an object that other objects borrow methods from. Methods live on the prototype, not on each object made from it.

A constructor and its prototype method

The constructor stores the name on each dog. The speak method lives on the prototype, and each dog reaches it from there.

function Dog(name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  console.log(this.name + " barks");
};
const rex = new Dog("Rex");
rex.speak();

Two objects share one method

Both dogs point at the same speak function. The check proves the two methods are one and the same function.

function Dog(name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  console.log(this.name + " barks");
};
const rex = new Dog("Rex");
const spot = new Dog("Spot");
console.log(rex.speak === spot.speak);
rex.speak();
spot.speak();

The method is not an own property

The keys of one dog list only its own data. The method is missing from that list because it lives on the prototype.

function Dog(name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  console.log(this.name + " barks");
};
const rex = new Dog("Rex");
console.log(JSON.stringify(Object.keys(rex)));

Example

function Car(model) {
  this.model = model;
}
Car.prototype.describe = function () {
  console.log("Car: " + this.model);
};
const car = new Car("Civic");
car.describe();
console.log(JSON.stringify(Object.keys(car)));

Key points

  • Prototype: an object that hands its methods down to objects made from it
  • A constructor function builds objects of one kind.
  • The new keyword runs a constructor and makes a fresh object.
  • Add a shared method to the constructor's prototype property.
  • Every object made by the constructor shares that one method.
  • A method on the prototype reads the object's own data through this.

In this example, the constructor stores the model on each car. The describe method lives on the prototype, so the car holds only its own model property. The keys list shows model and nothing else.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Where does a method added to Dog.prototype live?