JS Objects Explained: Literals, Constructors, Prototype Chains, and the Wrapper Classes Behind str.a
Misunderstanding the object model produces subtle bugs like silently lost properties and confusing equality checks. Knowing how V8 handles primitives, the prototype chain, and temporary wrappers gives developers a debugging edge when writing or refactoring JavaScript code.
JavaScript's object model trips up developers with behaviors like assigning a property to a string and reading back undefined. The explanation lies in how the language separates primitive values from reference types. Primitive values are compared by value, while objects are compared by address. This foundational distinction drives the way equality works, including why two identical-looking Symbols are never equal.
The article walks through six code experiments. Object literals and the three CRUD operations on key-value pairs are straightforward, but the real depth comes from constructors and the prototype chain. The `new` keyword does four hidden steps: create a blank object, wire its `__proto__` to the constructor's `prototype`, bind `this`, and return the object. All instances share methods placed on the prototype, and property lookup follows the chain from the object itself up to `Object.prototype` and then `null`.
The final piece is the wrapper class mechanism. Accessing a property on a primitive like `'hello'.length` triggers V8 to create a temporary wrapper object, attach the accessed property, and discard it immediately. That's why `str.a = 2` doesn't throw but also doesn't stick; the primitive itself never changes. In strict mode, the same action throws a TypeError.
The silent failure of setting a property on a primitive is a deliberate design choice: primitives stay lightweight, and the wrapper is ephemeral. This behavior neatly illustrates the boundary between JS's value types and object types.
Understanding the four steps of `new` is more useful than memorizing constructor syntax; it explains why methods belong on the prototype and why `this` in a constructor represents the new instance.
The prototype chain is essentially a shared memory mechanism; putting methods on the prototype saves memory but also means the same method is shared by all instances, a key performance consideration in larger applications.