HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Object Prototypes

Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype.


The Inheritance Blueprint

In the previous lesson, we learned about constructors. If you want to add a new property (or method) to a constructor, you have to add it to the constructor function definition itself. But what if the constructor is from a third-party library or you want to add something later? That's where Prototypes come in.


Using the prototype Property

The prototype property allows you to add new properties and methods to object constructors:

1. Adding a Property:

function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}

Person.prototype.nationality = "Bangladeshi";

2. Adding a Method:

Person.prototype.greet = function() {
  return "Hello, I am " + this.firstName;
};
Why use Prototypes? When you add a method to a prototype, it is only created once in memory and shared by all instances. If you add it inside the constructor, it is recreated for every single object, which uses more memory.

The Prototype Chain

When you try to access a property or method on an object, JavaScript first looks at the object itself. If it doesn't find it there, it looks at the object's prototype. This continues until it finds the property or reaches the end of the chain (null).


Modifying Built-in Prototypes

You can even add new methods to built-in JavaScript objects like Array or String. However, this is generally discouraged because it can lead to conflicts with other libraries or future versions of JavaScript.

// Adding a method to the built-in String prototype
String.prototype.sayHi = function() {
  return "Hi " + this;
};

"Mim".sayHi(); // "Hi Mim"

Key Points to Remember

  • All JavaScript objects inherit from a prototype
  • Use the prototype property to extend existing constructors
  • Memory Efficiency: Methods on prototypes are shared across all instances
  • The Prototype Chain is the mechanism behind JavaScript inheritance
  • Avoid modifying built-in prototypes to prevent coding "collisions"
  • The prototype is its own object, often referred to as __proto__ in code