JavaScript(JS) object method - create

ww‮ditfigi.w‬ea.com

The create method is a static method available on the Object constructor in JavaScript. It is used to create a new object with the specified prototype object and properties.

The syntax for using the create method is as follows:

Object.create(proto, [propertiesObject])

Here, proto is the prototype object to be used for creating the new object, and propertiesObject is an optional object that specifies the properties for the new object. If the propertiesObject argument is omitted or null, the newly created object will have no properties.

For example, let's say we have an object person with a name property:

const person = {
  name: 'John'
};

We can create a new object employee that has person as its prototype using the create method:

const employee = Object.create(person);

console.log(employee.name); // Output: 'John'

In this example, employee has person as its prototype, so it inherits the name property from person.

We can also specify additional properties for the new object using the propertiesObject argument:

const employee = Object.create(person, {
  job: {
    value: 'Developer'
  }
});

console.log(employee.job); // Output: 'Developer'

In this example, employee has a job property with a value of 'Developer'.