The Object.create()
method uses an existing object as a prototype to create a new object.
The Object.create()
method has the following prototypes:
Object.create(proto)
Object.create(proto, propertiesObject)
The Object.create()
function takes proto
as input in both prototypes, as well as an optional input, propertiesObject
, in the second prototype.
proto
: The prototype of the newly created object. proto
must be an object or null.propertiesObject
: The properties of the newly created object.The Object.create()
function returns a newly created object with the given prototype and properties.
The following example demonstrates how to create an object using the Object.create()
function in Javascript.
fruit
with the properties isFruit
and printFuit
.newFruit
, using fruit
as the prototype. It adds a new property, name
, to newFruit
and overwrites its existing property isFruit
.printFruit()
function, which displays information about the fruit using its properties.// create objectconst fruit = {isFruit: false,printFruit: function() {console.log(`Is ${this.name} a fruit? ${this.isFruit}`);}};// create a new objectconst newFruit = Object.create(fruit);// create a new propertynewFruit.name = 'Mango';// overwrite the isFruit propertynewFruit.isFruit = true;newFruit.printFruit();
Free Resources