In the world of JavaScript, object inheritance is a fundamental concept that allows us to create complex and reusable code. Two methods that play a crucial role in this process are Object.create()
and Object.setPrototypeOf()
.
In this article, we'll explore the differences between these two methods and provide up-to-date code examples to help you master object inheritance.
Object.create()
The Object.create()
method is a powerful tool for creating new objects with a specified prototype. This method allows you to create an object that inherits properties and methods from another object, without the need for the new
keyword or a constructor function. Here's an example of how to use Object.create()
:
// Create a base object
const baseObject = {
greet: function() {
console.log("Hello, from the base object!");
}
};
// Create a new object that inherits from the base object
const newObject = Object.create(baseObject);
// Call the inherited method
newObject.greet(); // Output: "Hello, from the base object!"