JavaScript Object create() method is used to create a new object with a specified prototype object and properties. The method takes one parameter, which is an object to be set as the new object’s prototype.
Object.create(proto, propertiesObject)
You can also provide an optional second parameter to Object.create() that specifies additional properties and methods for the new object.
The new object will inherit properties and methods from the prototype object. If the parameter is null
, the new object will not inherit any properties or methods.
JavaScript Object create() example
A simple example code creates a new object using the prototype of the given object.
<!DOCTYPE html>
<html>
<body>
<script>
const person = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return `${this.firstName} ${this.lastName}`;
}
};
const john = Object.create(person);
john.firstName = 'John';
john.lastName = 'Smith';
console.log(john.fullName());
</script>
</body>
</html>
Output:
You can also provide an optional second parameter to Object.create()
that specifies additional properties and methods for the new object.
const person = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return `${this.firstName} ${this.lastName}`;
}
};
const john = Object.create(person, {
age: { value: 30 },
occupation: { value: 'Programmer' }
});
console.log(john.age); // 30
console.log(john.occupation); // Programmer
Do comment if you have any doubts or suggestions on this Js object methods topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version