Mastering Prototypes & Inheritance in JS πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

JavaScript Prototypes and Prototype Inheritance

What are Prototypes?

In JavaScript, every object has an internal link to another object called its prototype. Prototypes allow objects to inherit properties and methods from other objects.

Example: Adding Methods Using Prototypes

function CreateTroop(name, target) {
    this.name = name;
    this.target = target;
}
 
CreateTroop.prototype.attack = function() {
    console.log(`${this.name} is Attacking`);
};
 
const barb = new CreateTroop("barbarian", "ground");
const archer = new CreateTroop("archer", "both");
 
barb.attack(); // barbarian is Attacking
archer.attack(); // archer is Attacking

Explanation:

  • CreateTroop: A constructor function.
  • CreateTroop.prototype.attack: Adds a method to the prototype, shared by all instances.
  • barb and archer: Instances of CreateTroop that inherit the attack method.

Prototype Inheritance

Prototype inheritance allows one constructor function to inherit properties and methods from another constructor function.

function User(name) {
    this.name = name;
    this.total = 56;
    this.print = function() {
        console.log(this);
    };
}
 
function Teacher(name, subject) {
    User.call(this, name); // Call User constructor
    this.subject = subject;
}
 
const t = new Teacher("DeathCode", "JS");
console.log(t);
t.print(); // Logs the Teacher instance

Explanation:

  • User.call(this, name): Inherits properties from the User constructor.
  • Teacher: A constructor function extending User.
  • t: An instance of Teacher, with properties from both Teacher and User.

Extending Built-in Prototypes

String.prototype.removeUnderscore = function() {
    return this.replaceAll('_', ' ');
};
 
let name = "Hello_Death_Code";
console.log(name.removeUnderscore()); // Hello Death Code

Explanation: Adds a custom method removeUnderscore to the String prototype.

Adding Methods to All Objects

Object.prototype.deathcode = function() {
    console.log("Hello Dosto, Subscribe krdo");
};
 
"".deathcode(); // Hello Dosto, Subscribe krdo

Explanation: Adds a method deathcode to the Object prototype, making it available to all objects.

Best Practices

  • Use prototypes to share methods between instances efficiently.
  • Be cautious when extending built-in prototypes to avoid conflicts.
  • Use Object.create or classes for more structured inheritance.
Β© 2024 DeathCode. All Rights Reserved.