Object.create() — a JavaScript Fundamental

Mai Pham
3 min readMay 22, 2021

In object-oriented programming we know the significance of classes and objects. However, unlike other programming languages, JavaScript does not have the traditional classes like other languages. But JavaScript has objects and constructors which work mostly in the same way to accomplish the same kind of operations.

Constructors

  • Constructors are general JavaScript functions which are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects).
Example 1
Example 2

Consider the examples above — both are written differently but are essentially the same thing. The function “Animal()” is an object constructor, and its properties and methods i.e “dog” is declared inside it by inferring it with the keyword “this”. Objects defined using an object constructor are then made instants by using the keyword “new”.

When new Animal() is called, JavaScript does two things:

  1. It creates a new object(instance), Animal() and assigns it to a variable of cat.
  2. It sets the constructor property i.e “cat” of the object to Animal.

Object.create()

  • Object.create()method is used to create a new object with the specified prototype object and properties. It is used for implementing inheritance.
  • It accepts two arguments and is written as:
    Object.create(prototype, propertiesObject)
    Prototype: prototype object from which a new object has to be created. It has to be an object or null.
    PropertiesObject: Optional parameter. Properties to be added to the newly created object.
The newly create object will inherit all the prototype object properties.

Consider the example above:
There are two functions “animals” and “dog”. A new instance of dog is created which is named as “pup” and it has been specified with the prototype and property of “animals” i.e. this.name = ‘Sammy’.

You can specify a second parameter to add new properties to the object, that the prototype lacked which in this case is age

In this example above, there are two functions “animals” and “dog”. A new instance of dog is created which is named as “pup” and it has been specified with the prototype and property of “animals” i.e. this.name = ‘Sammy’ and this.age = ‘10’. This is because the dog object inherited from the animals object.

This is how you create a new object in JS using Object.create() all the while implementing inheritance of the prototypes. Next week, I will discuss Prototype so stay tuned!

Resources you can read more about Object.create(), visit:

--

--