Ticker

6/recent/ticker-posts

Prototype in JavaScript

Prototype in JavaScript

Introduction Prototype is a fundamental concept in JavaScript that enables object-oriented programming and allows objects to inherit properties and methods from other objects. It serves as a blueprint or template for creating new objects with shared functionality.

Understanding Prototypes In JavaScript, every object has a prototype, except for the base object, which is the final link in the prototype chain. Each object's prototype is a reference to another object, forming a chain until the base object is reached.

Creating Prototypes There are multiple ways to create prototypes in JavaScript. One common approach is to use constructor functions.

Example: Creating a Prototype using Constructor Functions

javascript
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old."); }; var john = new Person("John", 30); john.greet(); // Output: Hello, my name is John and I am 30 years old.

Explanation:

  • We define a constructor function called Person that takes name and age as parameters. Inside the constructor, we assign these values to the respective properties of the newly created object.
  • We add a method called greet to the Person.prototype object. This method can be accessed by all instances of the Person constructor.
  • We create a new object john using the Person constructor and pass the values "John" and 30 for the name and age properties, respectively.
  • Finally, we invoke the greet method on the john object, which outputs a greeting message.

Modifying Prototypes Prototypes can be modified even after they have been created, and all objects that inherit from the prototype will reflect those changes.

Example: Modifying a Prototype

javascript
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old."); }; var john = new Person("John", 30); Person.prototype.introduce = function() { console.log("I am " + this.name + "."); }; john.introduce(); // Output: I am John.

Explanation:

  • We define the Person constructor and add the greet method to the Person.prototype object, as shown in the previous example.
  • After creating the john object, we modify the prototype by adding an introduce method.
  • The john object can now access the introduce method because it inherits from the modified prototype.

Summary Prototypes in JavaScript allow for object inheritance, providing a mechanism to share properties and methods among objects. They are created using constructor functions or can be modified dynamically. Understanding prototypes is crucial for effective JavaScript object-oriented programming.

Post a Comment

0 Comments