Sub topic 1
Objects and Property Lookup
Prerequisites
This chapter assumes you know object literals and property access, how this is bound in method calls, ES2015 syntax (const, arrow functions, template literals), and how to run code in Node.js or a browser console.
Every Object Has a Hidden Link: [[Prototype]]
An object holds its own properties. Every object also has an internal slot called [[Prototype]]. The slot points to another object, or to null. You cannot read the slot directly with dot notation. It decides where JavaScript looks next when a property is missing from the object.
A plain object literal such as {} gets Object.prototype as its prototype. That is why ({}).toString exists even though you never defined it.
Walking the Prototype Chain
To read obj.key, JavaScript checks obj's own properties first. If the key is missing, it follows [[Prototype]] and checks that object, and keeps going. The lookup stops at the first match. If it reaches null, the result is undefined.
Choosing a Prototype with Object.create
Object.create(proto) returns a new empty object whose [[Prototype]] is 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); // trueReading and Changing Prototypes: getPrototypeOf, setPrototypeOf, and __proto__
| API | Purpose | Recommendation |
|---|---|---|
| `Object.getPrototypeOf(obj)` | Read the prototype | Use it |
| `Object.setPrototypeOf(obj, p)` | Change the prototype after creation | Avoid. It is slow and engines deoptimize the object |
| `obj.__proto__` | Legacy getter/setter | Avoid in new code |
How this Works in Inherited Methods
The method walk is found on animal, but rabbit.walk() still sets this to rabbit. this comes from the object before the dot at call time. Where the method was found does not matter. This is why one method on a prototype can serve many objects.
A common error is to expect this to point at the prototype. Another is to pull the method off the object (const w = rabbit.walk; w()), which loses this completely.
Exercise
Given const base = { greet() { return this.id; } }; const x = Object.create(base); x.id = 7;, what do x.greet(), Object.hasOwn(x, 'greet'), and base.greet() return?
Show answer
x.greet() returns 7, because this is x. Object.hasOwn(x, 'greet') is false, because greet is inherited. base.greet() returns undefined, because base has no id and neither does Object.prototype.