Logo

Developer learning path

JavaScript

Prototype in JavaScript

Prototype

2

#description

In JavaScript, a prototype is an object that serves as a blueprint for other objects. Every JavaScript object has a prototype, which is inherited from the Object prototype object. A prototype-based approach is different from the class-based approach used in many other programming languages.

When you create a new object in JavaScript, it is linked to its prototype object through a special property called proto. This allows the object to access properties and methods defined on its prototype. If a property or method is not found in the object itself, JavaScript looks for it in its prototype and up the prototype chain until it reaches the Object prototype.

One of the most common use cases of prototypes in JavaScript is to add new methods or properties to an existing object. You can do this by modifying the prototype of the object's constructor function.

For example, suppose you have a Person constructor function that creates objects with a name and age property.

You can add a new method called "greet" to the Person prototype like this:

                    
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name);
};
                  

Now, all objects created with the Person constructor will have access to the "greet" method:

                    
var person = new Person("John", 25);
person.greet(); // outputs "Hello, my name is John"
                  

Prototyping can be a powerful tool for creating flexible and reusable code in JavaScript. However, it requires a good understanding of how prototypes work in order to use them effectively.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.