[[Prototype]]

Understanding [[Prototype]] in JavaScript

As a web developer, I have come across the concept of [[Prototype]] many times while working with JavaScript. In simple terms, [[Prototype]] is an internal property of an object that allows it to inherit methods and properties from its parent object.

Creating Objects with Prototype

Let's take a look at an example:


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

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

var person1 = new Person('Raju', 26);
var person2 = new Person('Sara', 30);

person1.greet(); // output: Hello, my name is Raju
person2.greet(); // output: Hello, my name is Sara

In this example, we create a Person constructor function that takes a name and age parameter. We then add a greet() method to the prototype of the Person object.

When we create new instances of the Person object using the 'new' keyword, they will inherit the properties and methods defined in the Person prototype. In this case, person1 and person2 will both have the name and age properties, as well as the greet() method.

Chaining Prototypes

We can also chain prototypes to create more complex objects. Let's take a look at another example:


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

Animal.prototype.sleep = function() {
  console.log(this.name + ' is sleeping');
}

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
  console.log(this.name + ' is barking');
}

var dog1 = new Dog('Buddy');

dog1.sleep(); // output: Buddy is sleeping
dog1.bark(); // output: Buddy is barking

In this example, we create an Animal constructor function with a sleep() method. We then create a Dog constructor function that calls the Animal constructor function and inherits its properties and methods.

We then chain the Dog prototype to the Animal prototype using Object.create(). This means that any properties or methods added to the Dog prototype will also be available to the Animal prototype.

Finally, we add a bark() method to the Dog prototype and create a new instance of the Dog object called 'dog1'. When we call the sleep() and bark() methods on dog1, it will inherit the properties and methods defined in both the Animal and Dog prototypes.

Conclusion

Understanding [[Prototype]] is essential when working with JavaScript objects. By using prototypes, we can create complex objects that inherit properties and methods from their parent objects, making our code more efficient and easier to maintain.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe