What are the differences between JavaScript's Object.create() and new Object()?
Rashid D
JavaScript provides two different approaches to create objects:Object.create() andnew Object(). Here are the differences between them:
1. Object Prototype:
-Object.create():
- Creates a new object with the specified prototype object.
- The prototype object becomes the [[Prototype]] of the newly created object.
-new Object():
- Creates a new empty object.
- The object's [[Prototype]] is set to the defaultObject.prototype.
2. Syntax:
-Object.create():
- Accepts a prototype object as its first argument.
- Optionally, a second argument can be provided to define additional properties and descriptors for the created object.
-new Object():
- Doesn't accept any arguments.
- An empty object is created using the defaultObject constructor.
3. Object Inheritance:
-Object.create():
- Allows you to create an object that inherits from a specified prototype object.
- You can establish prototypal inheritance by specifying the prototype object explicitly.
-new Object():
- Creates a plain object without any inheritance.
- The created object inherits from the defaultObject.prototype.
4. Usage:
-Object.create():
- Useful when you want to create objects with specific prototypes.
- Enables you to implement inheritance and object composition patterns.
-new Object():
- Typically used when you need to create a generic object without any specific prototype or additional properties.
Here's an example to demonstrate the differences:
In the example above, we create a new objectperson usingObject.create() withpersonPrototype as its prototype. Theperson object inherits thegreet() method frompersonPrototype. On the other hand, we create two empty objects,emptyObject, andliteralObject, usingnew Object() and object literal syntax ({}). These objects are plain objects without any specific prototype or additional properties.
In summary,Object.create() is primarily used when you want to create objects with specific prototypes and establish inheritance, whilenew Object() is used to create generic objects without any specific prototype or additional properties. The choice between them depends on your specific use case and the desired object structure.