Sub topic 3
Choosing a Prototype with Object.create
This chapter assumes you can write object literals, call methods, and know that every object has a hidden [[Prototype]] link that property lookup follows. An object literal always links to Object.prototype. Object.create lets you pick the prototype yourself.
The basic call
Object.create(proto) returns a new, empty object whose [[Prototype]] is proto. The new object has no own properties of its own. Anything it can't find on itself 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); // truerabbit has only one own property, name. Reading rabbit.eats misses on rabbit and finds the value on animal. Calling rabbit.walk() also finds walk on animal. Inside the method, this is still rabbit, because this depends on the object before the dot, not on where the method is stored.
Defining properties at creation time
Object.create takes an optional second argument: an object of property descriptors, the same format Object.defineProperties uses.
const animal = { eats: true };
const hare = Object.create(animal, {
name: { value: 'Hare', enumerable: true },
speed: { value: 60, writable: true }
});
console.log(hare.name); // "Hare"
console.log(hare.speed); // 60
console.log(Object.keys(hare)); // ['name']
hare.name = 'Other';
console.log(hare.name); // "Hare" (not writable)Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `Object.create()` with no argument | `TypeError`: the prototype must be an object or `null` | Pass an object or `null` |
| `Object.create(animal, { name: 'Hare' })` | `TypeError`, because `'Hare'` is not a descriptor | Use `{ name: { value: 'Hare' } }` |
| Expecting `animal`'s properties to be copied | Nothing is copied. Later changes to `animal` show up through `rabbit` | This is how linking works. Copy with `Object.assign` if you need a snapshot |
Passing null gives you an object with no prototype at all. A later chapter covers that case.
Exercise
After running const base = { greet() { return 'hi ' + this.id; } }; const x = Object.create(base); x.id = 7; base.greet = function () { return 'bye ' + this.id; };, what does x.greet() return, and why?
Show answer
It returns "bye 7". Object.create links x to base instead of copying from it, so lookup finds the current greet on base. Inside the method, this is x, so this.id is 7.
Exercise
Write one call that creates an object cat with prototype animal and an own, enumerable, writable property name set to 'Tom'.
Show answer
const cat = Object.create(animal, { name: { value: 'Tom', enumerable: true, writable: true } });