CodeBlanks Logo Icon CodeBlanks

What is a prototype?

JavaScript course · Advanced · Lesson 13/100

Learn the prototype object every object links to and the shared behavior.

What is a prototype?

In JavaScript, every object links to another object called its prototype. Through this link, objects share behavior defined on the prototype. When you access a property, the engine checks the object first, then its prototype.

function Animal(name) {
  this.name = name;
}
Animal.prototype.describe = function () {
  return this.name + ' is an animal';
};

Every Animal object now reuses one shared describe function.

Why use prototype?

If you add the same method to each object one by one, every object carries its own copy. This wastes memory. A method added to the prototype stays as a single copy that all objects reach.

function Animal(name) { this.name = name; }
Animal.prototype.describe = function () {
  return this.name;
};

This way, even with hundreds of objects, a single function lives in memory.

Exercise Write the Animal constructor and prototype method

Define a constructor named Animal that takes a name parameter and assigns it to this.name. Then add a function to Animal.prototype.describe that returns the string this.name + ' is an animal'. Create an object rex with new Animal('Rex') and call console.log(rex.describe()).

Show example solution
function Animal(name) {
  this.name = name;
}
Animal.prototype.describe = function () {
  return this.name + ' is an animal';
};
const rex = new Animal('Rex');
console.log(rex.describe());

Test yourself

  1. What does Animal.prototype.describe provide?

    const rex = new Animal('Rex');
    rex.describe(); // 'Rex is an animal'
    • A separate function for each Animal object
    • One shared function used by all Animal objects
    • A function only the first Animal object can use
    • It hides the name property
    Show answer

    One shared function used by all Animal objects — Correct! A method on prototype is shared by all objects.

  2. Complete the describe method

    Animal.prototype.describe = function () {
      return this.name + ____;
    };
    Show answer
    Animal.prototype.describe = function () {
      return this.name + ' is an animal';
    };
  3. Match the prototype terms

    prototype
    shared behavior
    __proto__
    object's link
    constructor
    object factory
    new
    new instance

All lessons in Advanced