Prototype-Based OOP in JavaScript
JavaScript uses a prototype-based approach to object-oriented programming, which means that objects can inherit properties and methods directly from other objects. Every JavaScript object has an internal link to another object called its prototype. When you try to access a property or method on an object, JavaScript first looks for that property on the object itself. If it does not find it, it looks up the prototype chain, searching each prototype in turn until it finds the property or reaches the end of the chain.
This system allows you to share methods and properties efficiently between objects. Rather than duplicating functions for every object instance, you can attach methods to a constructor function's prototype. All objects created by that constructor will then have access to those shared methods via the prototype chain.
12345678910111213141516// Constructor function for creating Person objects function Person(name) { this.name = name; } // Add a method to the prototype Person.prototype.greet = function() { return "Hello, my name is " + this.name; }; // Create two instances const alice = new Person("Alice"); const bob = new Person("Bob"); console.log(alice.greet()); // Output: Hello, my name is Alice console.log(bob.greet()); // Output: Hello, my name is Bob
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Awesome!
Completion rate improved to 6.25
Prototype-Based OOP in JavaScript
Glissez pour afficher le menu
JavaScript uses a prototype-based approach to object-oriented programming, which means that objects can inherit properties and methods directly from other objects. Every JavaScript object has an internal link to another object called its prototype. When you try to access a property or method on an object, JavaScript first looks for that property on the object itself. If it does not find it, it looks up the prototype chain, searching each prototype in turn until it finds the property or reaches the end of the chain.
This system allows you to share methods and properties efficiently between objects. Rather than duplicating functions for every object instance, you can attach methods to a constructor function's prototype. All objects created by that constructor will then have access to those shared methods via the prototype chain.
12345678910111213141516// Constructor function for creating Person objects function Person(name) { this.name = name; } // Add a method to the prototype Person.prototype.greet = function() { return "Hello, my name is " + this.name; }; // Create two instances const alice = new Person("Alice"); const bob = new Person("Bob"); console.log(alice.greet()); // Output: Hello, my name is Alice console.log(bob.greet()); // Output: Hello, my name is Bob
Merci pour vos commentaires !