Τι είναι η πρωτότυπη κληρονομιά στην JavaScript;
sobes.tech AI
Απάντηση από AI
In JavaScript, objects inherit properties and methods from their prototypes. Each object's prototype is another object, whose properties and methods are accessible through the prototype chain.
When accessing a property of an object, JavaScript first looks directly in the object itself. If the property is not found, the search continues in the object's prototype, then in the prototype's prototype, and so on, until the property is found or the end of the chain (null) is reached.
Prototypical inheritance differs from classical inheritance (like in Java or C++), where objects are created from classes that describe their structure and behavior. In JavaScript, classes introduced in ES6 are syntactic sugar over prototypical inheritance.
Main aspects:
- __proto__: Internal property of the object referencing its prototype.
- prototype: Property of the constructor (function used as a constructor), referencing the object that will serve as the prototype for created instances.
- Object.getPrototypeOf(obj): Standard method to get the prototype of an object.
- Object.setPrototypeOf(obj, proto): Standard method to set the prototype of an object.
Example:
// Constructor function
function Animal(name) {
this.name = name;
}
// Add method to Animal's prototype
Animal.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
// Create an instance
const dog = new Animal("Buddy");
// Call method from prototype
dog.sayHello(); // Output: Hello, my name is Buddy
// The prototype of dog is Animal.prototype
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
// The prototype of Animal.prototype is Object.prototype
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true
// End of the prototype chain is null
console.log(Object.getPrototypeOf(Object.prototype) === null); // true
Comparison with classical inheritance (using ES6 classes):
class Animal {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent class constructor
this.breed = breed;
}
bark() {
console.log("Woof!");
}
}
const buddy = new Dog("Buddy", "Golden Retriever");
buddy.sayHello(); // Output: Hello, my name is Buddy (inherited from Animal)
buddy.bark(); // Output: Woof! (Dog method)
// Classes in ES6 are syntactic sugar over prototypes
console.log(Object.getPrototypeOf(Dog) === Animal); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.getPrototypeOf(buddy) === Dog.prototype); // true
Prototypical inheritance is a key concept in JavaScript, and understanding it is essential for effective work with the language.