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
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 6.25
Prototype-Based OOP in JavaScript
Sveip for å vise menyen
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
Takk for tilbakemeldingene dine!