Frontend Development: Inheritance and Prototype Chain

Peter Jeon·2023년 6월 21일
0

Frontend Development

목록 보기
25/80
post-custom-banner

Inheritance and Prototype Chain

In JavaScript, almost everything is an object. JavaScript is a prototype-based language, which means that inheritance in JavaScript is based on prototypes. In this blog, we'll be examining the concept of prototype chains and how they facilitate inheritance.

Inheritance in JavaScript

Inheritance

Inheritance is an important concept in object-oriented programming. It's a way to create a new class using classes that have already been defined. The newly formed classes, known as derived classes, inherit attributes and behavior of the pre-existing classes, which are referred to as base classes.

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

Animal.prototype.speak = function () {
  console.log(this.name + ' makes a noise.');
}

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

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

let dog = new Dog('Rover');
dog.speak(); // Rover makes a noise.

In the above code, Dog is a derived class that inherits from the Animal base class.

Prototype Chain

When it comes to inheritance in JavaScript, the prototype chain is the underlying concept. When a method is called on an object, JavaScript will try to find this method in the object itself. If it cannot find it, it will look for it in the object's prototype. This process continues up the chain until the method is found or until it reaches an object with a null prototype.

let animal = {
  eats: true
};

let rabbit = {
  jumps: true
};

rabbit.__proto__ = animal;

console.log(rabbit.eats); // true

In this code, the rabbit object inherits the eats property from the animal object.

Constructor Property

Every function has a property named prototype that is used during the creation of new instances. That prototype object is shared among all of the object instances, and it should contain only methods and properties that need to be shared among objects.

function Rabbit(name) {
  this.name = name;
}
Rabbit.prototype.sayHi = function() {
  console.log(this.name);
};
let rabbit = new Rabbit("Rabbit");

rabbit.sayHi();            // Rabbit
Rabbit.prototype.sayHi();  // undefined

In the above code, we see that the method sayHi is shared among all instances of the Rabbit object.

Conclusion

In conclusion, understanding the prototype chain and inheritance in JavaScript is crucial for effective JavaScript programming, particularly if you're working on larger or more complex projects. It's the foundation of how objects interact with each other in the language, and by understanding it, we can write more efficient and effective code.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글