Sometimes, we want to extend an object in JavaScript.
In this article, we’ll look at how to extend an object in JavaScript.
How to extend an object in JavaScript?
To extend an object in JavaScript, we can use the Object.create
method.
For instance, we write
const person = {
name: "",
greet() {
console.log(`Hi, I am ${this.name}.`);
},
};
const jack = Object.create(person);
jack.name = "Jack";
jack.greet();
to call Object.create
with person
to create an object that inherits the prototypes of person
and the properties in person
.
Then we add the name
property to the jack
object and call greet
on it.
The greet
method then should log 'Hi, I am Jack.'
.
Conclusion
To extend an object in JavaScript, we can use the Object.create
method.