JS Object.create
In this page:
Creating an Object
Object.create creates a new object with the prototype you provide. This is a more direct way to set up inheritance than using a constructor function, since you specify the exact prototype object up front.
Example: Creating an Object
const proto = { greet() { return "hi"; } };
const obj = Object.create(proto);
console.log(obj.greet());
Using null as Prototype
Object.create(null) makes an object without Object.prototype in its prototype chain. This is useful for building a genuinely empty object with no inherited methods at all — safer than a plain {} when you want to avoid accidental prototype pollution or collisions.
Example: Using null as Prototype
const obj = Object.create(null);
obj.name = "Sam";
console.log(obj.name);
console.log(obj.toString); // undefined, no inherited methods
Adding Properties
The second argument can define properties while the object is created. Using a descriptor object lets you also mark a property as non-writable or non-enumerable at the moment of creation, not just set its initial value.
Example: Adding Properties
const obj = Object.create({}, {
name: { value: "Sam", writable: true },
});
console.log(obj.name);
Property Descriptors
Property descriptors control whether a property can be changed, shown in loops, or removed. Descriptors give fine-grained control that plain assignment doesn't offer, like making a property read-only or invisible to for...in loops and Object.keys().
Example: Property Descriptors
const obj = {};
Object.defineProperty(obj, "id", { value: 1, writable: false, enumerable: false });
obj.id = 99; // silently fails, read-only
console.log(obj.id);
console.log(Object.keys(obj)); // [], hidden from enumeration
Object.create in Practice
Object.create is useful when you want shared behavior or a custom prototype. It's commonly reached for when you want an object that behaves like a specific prototype's instance without going through a constructor function or class at all.
Example: Object.create in Practice
const carPrototype = { drive() { console.log("Driving"); } };
const myCar = Object.create(carPrototype);
myCar.drive();
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: