» Quick Introduction to JavaScript » 2. Advanced » 2.2 Prototypes

Prototypes

In JavaScript, every object has a prototype, and objects can inherit properties and methods from their prototype. Since functions are basically objects, so they also have prototypes.

// Constructor function for a 'Person' object
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// Adding a method to the prototype of the 'Person' constructor
Person.prototype.sayHello = function () {
  console.log('Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.');
};

// Creating instances of the 'Person' object
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);

// Calling the 'sayHello' method inherited from the prototype
person1.sayHello(); // Output: Hello, my name is Alice and I am 25 years old.
person2.sayHello(); // Output: Hello, my name is Bob and I am 30 years old.

Inheritance

You can achieve inheritance using prototypes.

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function () {
  console.log('I am ' + this.name);
};

function Dog(name, breed) {
  // Call the parent constructor using 'call'
  Animal.call(this, name);
  
  // Additional property specific to Dog
  this.breed = breed;
}

// Set up the prototype chain: Dog.prototype inherits from Animal.prototype
Dog.prototype = Object.create(Animal.prototype);


// Adding a method specific to Dog to its prototype
Dog.prototype.bark = function () {
  console.log('Woof! Woof!');
};

// Creating instances
const myDog = new Dog('Buddy', 'Golden Retriever');
myDog.sayName(); // Output: I am Buddy
myDog.bark();    // Output: Woof! Woof!

The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.

Code Challenge

Override calculateArea method in the Circle and Rectangle prototypes to calculate the area specific to each shape.

Loading...
> code result goes here
Prev
Next