Loading...
Loading...

Understanding JavaScript Prototypes

JavaScript prototypes are a powerful feature that allows for inheritance and the creation of object-oriented code. This tutorial will explore how prototypes work and how to use them effectively.

1. What is a Prototype?

A prototype is an object that is associated with every function and object in JavaScript by default. It allows you to define properties and methods that can be shared across all instances of an object.

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

2. Adding Methods to Prototypes

You can add methods to an object's prototype to make them available to all instances of that object.

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

Example:

const alice = new Person("Alice");
alice.greet(); // Output: Hello, Alice

3. Prototype Inheritance

JavaScript allows for prototype inheritance, where one object can inherit properties and methods from another.

function Student(name, major) {
    Person.call(this, name);
    this.major = major;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.study = function() {
    console.log(this.name + " is studying " + this.major);
};

Example:

const bob = new Student("Bob", "Mathematics");
bob.greet(); // Output: Hello, Bob
bob.study(); // Output: Bob is studying Mathematics

4. Checking Prototypes

You can check if an object has a certain property or method by using the hasOwnProperty method or by using the in operator.

console.log(bob.hasOwnProperty("major")); // Output: true
console.log("greet" in bob); // Output: true

5. Modifying Prototypes

You can modify prototypes at any time, and all instances of the object will reflect these changes.

Person.prototype.walk = function() {
    console.log(this.name + " is walking.");
};

Example:

alice.walk(); // Output: Alice is walking.

Conclusion

Understanding prototypes in JavaScript is essential for mastering object-oriented programming. Prototypes allow for inheritance and code reusability, making your code cleaner and more efficient.

0 Interaction
1.3K Views
Views
15 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home