Objects, Prototypes and Classes
Objects are bags of properties linked into prototype chains. Know how lookup, assignment and definition differ, what classes really create, and the order in which constructors and fields run.
Key points
- 1
Reads walk the prototype chain; plain assignment normally creates an own property that shadows the inherited one. An inherited setter or read-only property changes that: the setter runs instead, or the write fails (throwing in strict mode).
- 2
Every property has attributes: data properties have
value/writable, accessors haveget/set, and both haveenumerable/configurable. Assignment creates all-true attributes;Object.definePropertydefaults omitted ones tofalse. - 3
Own keys are ordered: array-index keys ascending, then other strings in insertion order, then symbols.
Object.keys= own enumerable strings,Reflect.ownKeys= every own key,for...in= enumerable strings including inherited ones. - 4
new F()links a fresh object toF.prototype, runsFwith it asthis, and returns it unlessFreturns an object. Classes add rules: they must be called withnew, their bodies are strict, and statics are inherited throughChild → Base. - 5
Field order: in a base class, fields are set before the constructor body; in a derived class,
thisis unusable untilsuper()returns, and then the derived fields are initialised. Fields use define semantics, so they skip inherited setters. - 6
Private
#namesare not properties: freeze, spread andObject.keysdon't see them,#x in objis a brand check, and reading a missing private field throws aTypeError. - 7
Object.assignuses get/set (getters run, target setters run). Object spread defines data properties on a new plain object. Both are shallow and drop the prototype; copy descriptors to keep accessors, and usestructuredClonefor deep copies of plain data.
Common traps
Calling an overridden method from a base constructor runs the subclass method before the subclass's fields exist.
obj.__proto__ = xonly changes the prototype whenobjinherits the__proto__accessor. Null-prototype objects and computed or JSON keys create an ordinary property instead, which is the root of prototype-pollution bugs.this.constructor.count++on an inherited static creates a new own static on the subclass instead of updating the base class's counter.
Test yourself on Objects, Prototypes and Classes
Ten questions, with the answer and explanation after each one.