How to create object without prototype in JavaScript?
When we create an object using object literal, JavaScript uses an object constructor to create the object. This allows the new object to inherit properties from Object.prototype
Let us consider the following example:
const newObject = {}; console.log(newObject.constructor); // Outputs: ƒ Object() { [native code] }
We can clearly see from the above code segment, newObject
is an object literal. JavaScript behind the scene used an object constructor to create the object. We are able to get the constructor of the object literal.
If we want to create an object without the prototype chain, we can use Object.create
. We need to pass null
when using Object.create
.
The following is an example:
const userObj = Object.create(null, { name: {value: 'Joe Smith'} }); // Outputs: undefined console.log(userObj.constructor);
The first argument to Object.create
is null
. Normally this is where we would pass in the object that we want to serve as the prototype. As null
is used, the new object doesn’t inherit from the prototype at all.