In this video, you answer two questions left over from Mei’s Plant class: where the one copy of each shared method lives, and where Goldie’s default .toString() came from before Mei wrote her own. In a short session in Node’s REPL, with a cut-down Plant class, you follow a property lookup link by link, from Goldie up to the end of the chain.
Key Points
- An own property is one an object holds itself.
Object.hasOwn(object, "name")asks about own properties only: Goldie’s only own property is hername, soObject.hasOwn(goldie, "describe")isfalse, even thoughgoldie.describe()works. - Every object has a hidden link, its prototype, to another object, or to
null, which marks the end of the chain.Object.getPrototypeOf(goldie)hands you the object at the other end of Goldie’s link:Plant.prototype. - A class builds that object. The class makes an object for its plants to link to, puts its methods there, and keeps it in its
prototypeproperty,Plant.prototype. That property isn’t the prototype link ofPlantitself.newmakes each plant’s link when it makes the plant, which is why everyPlantshares one copy of each method. - Reading a property walks the chain. JavaScript looks on the object first, then follows the links, one prototype at a time, until it finds the property, or reaches
nulland stops. A method found on a prototype is still called with the object before the dot, sothisis still Goldie. - The chain for a plant is the instance, then
Plant.prototype, thenObject.prototype, whose own prototype isnull. The default.toString()lives onObject.prototype, and a property no object on the chain has, such asgoldie.color, givesundefined. - Arrays work the same way. An array, like the lists of records you’ve built since the basics, has no
mapof its own: its prototype isArray.prototype, where.map()and the other array methods live. That’s why every array has.map(). - An assignment like Spike’s makes an own property. When Mei assigns Spike his own
describe, a function expression, the assignment puts it on Spike and leavesPlant.prototypeuntouched. Spike’s owndescribeshadows the shared one, for Spike alone: Goldie still finds thedescribeonPlant.prototype. inversusObject.hasOwn():"toString" in goldieistrue, becauseinsearches the whole chain, whileObject.hasOwn(goldie, "toString")isfalse, because it looks at Goldie alone.Object.keys()versusfor...in:Object.keys(goldie)lists own keys only,[ 'name' ]. Afor...inloop can also reach keys on the chain, but only enumerable ones, keys whose enumerable flag says loops should list them. Class methods and the.toString()onObject.prototypearen’t enumerable, so the loop over Goldie skips them and printsnametoo, the same asObject.keys().
The REPL Session
Run node with no file name, and type each line after the > prompt. The ... lines are Node’s continuation prompts for the class: