Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Introduction to Prototypes in JavaScript

Tech Oct 10 15

Understanding Prototypes in JavaScript

When we create a class using a constructor function, memory pre-allocates an object caled the prototype object. The constructor function has a prototype property pointing to this object, and the prototype object has a constructor property pointing back to the constructor function. You can access a class's prototype via ClassName.prototype.

Relationship Between Constructor and Prototype

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

    this.eat = function(food) {
        console.log(`${this.age} year old ${this.name} is eating ${food}`);
    };
}

console.log(Person);           // Constructor (function) object
console.log(Person.prototype); // Prototype object

Relationship Between Instances and Prototype

Every instance of a class has an internal __proto__ property pointing to their prototype. When accessing a property or method on an object, if its not found on the object itself, the lookup continues to the prototype. Therefore, we can add properties and methods to the prototype to share them among all instances of a class.

// Add properties and methods to the prototype
Person.prototype.gender = 'male';
Person.prototype.sleep = function() {
    console.log(`${this.age} year old ${this.gender} child ${this.name} is sleeping`);
};

const p1 = new Person('Alice', 10);
p1.eat('egg tart');
p1.sleep();

const p2 = new Person('Bob', 8);
p2.eat('croissant');
p2.sleep();

console.log(p1);
console.log(p2);

In the example above, gender and sleep are defined on the prototype, so all instances share them. The eat method is defined inside the constructor, so each instance has its own copy.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.