Using the Object.create() method for prototypal inheritance

Posted by

Using the Object.create() Method for Prototypal Inheritance

Prototypal inheritance is one of the core concepts of object-oriented programming (OOP). It is a way for objects to inherit properties from other objects without the need for classes.

The Object.create() method is a native JavaScript method that can be used to create an object with a given prototype. It allows you to easily create objects that inherit from other objects, avoiding the need to define classes.

Syntax

The syntax for the Object.create() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

Object.create(prototype, [properties]);

[/dm_code_snippet]

The prototype argument is the object that will be used as the prototype for the new object being created. The optional properties argument is an object that contains properties and their associated values for the new object.

Example

Let’s look at an example of using Object.create() to create a prototype:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

const parent = {
  name: 'Parent',
  sayName() {
    return this.name;
  }
};

const child = Object.create(parent);
child.name = 'Child';

console.log(child.sayName()); // 'Child'

[/dm_code_snippet]

In the example above, we first create an object named parent. This object contains a name property and a sayName() method. We then use the Object.create() method to create an object named child, with parent as its prototype. We then set the name property of the child object to 'Child'. Finally, we log the result of calling the sayName() method on the child object to the console.

Since the child object inherits from the parent object, it has access to the sayName() method. When we call this method on the child object, it returns the value of the name property of the child object, which is 'Child'.

Conclusion

The Object.create() method is a useful tool for creating objects that inherit from other objects without the need for classes. It is a native JavaScript method, so no additional libraries are needed. It is also easy to use and understand, making it a great choice for prototypal inheritance.