JavaScript Object.create() Example

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

Syntax

Object.create(proto, [propertiesObject])
  • proto - The object which should be the prototype of the newly-created object.
  • propertiesObject (Optional) - If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties().

Examples

Let's demonstrate use of Object.create() method which creates an object which has a specified prototype and optionally contains specified properties as well (e.g Object.create( prototype, optionalDescriptorObjects )).
In this example, we have an Employee object that we use as the prototype to create another object employee1 with JavaScript’s Object.create feature:
// using Object.create Method 
var Employee = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
} 

var employee1 = Object.create(Employee);

// access new object properties
console.log('firstName :',  employee1.firstName);
console.log('lastName :',  employee1.lastName);
console.log('emailId :',  employee1.emailId);
console.log('age :',  employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
As we know Object.create() method has two parameters. A first parameter is a mandatory object that serves as the prototype of the new object to be created and this we have demonstrated in the above example. A second parameter is an optional object which contains the properties to be added to the new object. For example, we are adding emailId and age properties to the new object here:
// using Object.create Method
var Employee = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
} 

var employee1 = Object.create(Employee,{
 
  "emailId": {
    value: "ramesh@gmail.com",
    // writable:false, configurable:false by default
    enumerable: true
  },
 
  "age": {
    value: 29,
    enumerable: true
  }
 
});

// access new object properties
console.log('firstName :',  employee1.firstName);
console.log('lastName :',  employee1.lastName);
console.log('emailId :',  employee1.emailId);
console.log('age :',  employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29

Reference


Comments