Home >Web Front-end >JS Tutorial >JavaScript&#s Prototype-Based Inheritance Example

JavaScript&#s Prototype-Based Inheritance Example

Barbara Streisand
Barbara StreisandOriginal
2024-10-03 14:20:30990browse

JavaScript

Revisit the fundamental concept of prototype-based inheritance and unlock the full potential of JavaScript. Discover how objects can inherit properties and methods from their prototypes and simplify your code. Take your development skills to the next level!

`
// Create a simple object
let animal = {
sound: function() {
console.log("The animal makes a sound");
}
};

// Create a new object that inherits from animal
let dog = Object.create(animal);
dog.sound(); // Output: The animal makes a sound

// Add a new method to the dog object
dog.bark = function() {
console.log("The dog barks");
};

// Create a new object that inherits from dog
let myDog = Object.create(dog);
myDog.bark(); // Output: The dog barks
myDog.sound(); // Output: The animal makes a sound
`

The above is the detailed content of JavaScript&#s Prototype-Based Inheritance Example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn