Sub topic 4
Choosing a Prototype with Object.create
The earlier chapters showed that every object has a hidden [[Prototype]] link and that property lookup follows that link up the chain. Object literals always link to Object.prototype. To make an object inherit from an object you pick, use Object.create.
This chapter assumes you know object literals, property access, and how this is bound in a method call. You should also have Node.js or a browser console open to run the examples.
The Basic Call
Object.create(proto) returns a new, empty object whose [[Prototype]] is proto. It has no own properties. Any property you read that the object lacks is looked up on proto.
const animal = {
eats: true,
walk() {
return `${this.name} walks`;
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
console.log(rabbit.eats); // true (inherited)
console.log(rabbit.walk()); // "Rabbit walks"
console.log(Object.getPrototypeOf(rabbit) === animal); // true
console.log(Object.hasOwn(rabbit, 'eats')); // false
console.log('eats' in rabbit); // trueThese results follow directly from the lookup rules:
rabbit.eatsis not an own property, so lookup moves toanimaland findstruethere.rabbit.walk()findswalkonanimal, but the call happens throughrabbit, sothisisrabbit. Itsnameis'Rabbit'.Object.getPrototypeOfreturns the[[Prototype]]link. It is the one we passed in.Object.hasOwnchecks only the object itself. Theinoperator checks the whole chain.
Note that animal itself was created by a literal, so the chain continues past it to Object.prototype. Because of that, rabbit.toString() still works.
The Link Is Live
Object.create does not copy anything. It stores a reference. Any change you make to the prototype later shows up on every object that links to it.
const base = { greet() { return 'hello'; } };
const obj = Object.create(base);
base.farewell = function () { return 'bye'; };
console.log(obj.farewell()); // "bye"
delete base.greet;
console.log(obj.greet); // undefinedThis is called delegation. The object hands the lookup to its prototype each time a property is read. It is not a snapshot taken when the object was created.
Building Longer Chains
You can pass an object that already has a prototype, and the chain gets one level longer each time.
const living = { alive: true };
const animal = Object.create(living);
animal.eats = true;
const rabbit = Object.create(animal);
rabbit.jumps = true;
console.log(rabbit.alive, rabbit.eats, rabbit.jumps); // true true true
console.log(living.isPrototypeOf(rabbit)); // trueLookup for alive checks rabbit, then animal, then living. Long chains work, but each missing level costs one more step on a failed lookup, and they get harder to reason about. Two or three levels are usually enough.
The Second Argument: Property Descriptors
Object.create accepts an optional second argument. It is an object that maps property names to property descriptors, in the same format that Object.defineProperties takes. This lets you create the object and define its own properties in a single step.
const pointProto = {
toString() {
return `(${this.x}, ${this.y})`;
}
};
const p = Object.create(pointProto, {
x: { value: 1, writable: true, enumerable: true, configurable: true },
y: { value: 2 } // all flags default to false
});
console.log(String(p)); // "(1, 2)"
console.log(Object.keys(p)); // ['x']
p.y = 99; // ignored in sloppy mode, TypeError in strict mode
console.log(p.y); // 2You can also define getters and setters in the descriptor map with get and set instead of value.
What You Can Pass as the Prototype
The first argument has to be an object or null. Anything else throws an error.
try {
Object.create(undefined);
} catch (e) {
console.log(e instanceof TypeError); // true
}
const empty = Object.create(null);
console.log(Object.getPrototypeOf(empty)); // nullThe usual cause of this error is a prototype variable that has not been set yet, such as a typo or an import that resolved to undefined. Passing null is valid and gives you an object with no prototype at all. A later chapter covers why that is useful for dictionaries.
Comparing Ways to Make an Object
| Expression | Resulting `[[Prototype]]` | Own properties |
|---|---|---|
| `{}` | `Object.prototype` | none |
| `Object.create(Object.prototype)` | `Object.prototype` | none |
| `Object.create(proto)` | `proto` | none |
| `Object.create(proto, descriptors)` | `proto` | those in `descriptors` |
| `Object.create(null)` | `null` | none |
An empty literal {} and Object.create(Object.prototype) produce the same result. Literals are simply the common case written in shorter form.
Common Errors
- Expecting a copy.
Object.create(source)does not clonesource.Object.keys(copy)returns[]and changes tosourceshow through. To copy, use{ ...source }orstructuredClone. - Putting per-object data on the prototype. If the prototype holds an array or an object, every object that inherits it shares that same value. Keep per-object data as own properties set after
create. A later chapter covers this pitfall in detail. - Forgetting descriptor defaults. Use an explicit
writable: true, enumerable: true, configurable: true, or assign properties after creation. - Serializing inherited data.
JSON.stringifyandObject.keysignore inherited properties, so values that live on the prototype disappear from the output.
A Small Factory Pattern
Object.create is enough for sharing behavior without constructors. Put the methods on one prototype object, then write a function that creates instances and gives each one its own state.
const counterProto = {
increment() {
this.count += 1;
return this.count;
}
};
function createCounter(start = 0) {
const c = Object.create(counterProto);
c.count = start;
return c;
}
const a = createCounter();
const b = createCounter(10);
console.log(a.increment(), b.increment()); // 1 11
console.log(a.increment === b.increment); // true (shared method)Both counters share a single increment function but keep separate count values. Constructor functions and classes, covered in later chapters, automate this same arrangement.
Exercise
Given const proto = { kind: 'base' }; const o = Object.create(proto, { id: { value: 7 } });, what do o.kind, Object.keys(o), and JSON.stringify(o) return, and why?
Show answer
o.kind is 'base' because lookup finds it on the prototype. Object.keys(o) is [] because the only own property, id, was defined without enumerable: true and so is non-enumerable, and kind is inherited. JSON.stringify(o) is '{}' for the same reasons: it serializes only own enumerable properties.
Exercise
After running const a = Object.create({ x: 1 }); const proto = Object.getPrototypeOf(a); proto.x = 2;, what is a.x? What would it be if a had been created with { ...{ x: 1 } } instead?
Show answer
a.x is 2, because a delegates to the live prototype object that was changed. With the spread version, a has its own copy x: 1, and its prototype is Object.prototype, so a.x stays 1 and setting proto.x would add x to Object.prototype instead, which you should never do.