跪拜 Guibai
← Back to the summary

JS Objects Explained: Literals, Constructors, Prototype Chains, and the Wrapper Classes Behind str.a

Thoroughly Understanding JS Objects: From Literals, Constructors to Prototype Chains and Wrapper Classes

It's recommended to manually type out the code snippets in the article, change a few values, and run them again. That works much better than just reading.

When learning JS, you've likely written code like this:

let str = 'hello'
str.a = 2
console.log(str.a)   // undefined

Strange? No error, but the property wasn't added either.

Now consider these two lines:

let a = 'hello'
let b = 'hello'
console.log(a === b)          // true

let c = Symbol('a')
let d = Symbol('a')
console.log(c === d)          // false

They look identical, but why is one equal and the other not?

The answers to these questions all point to the same thing — objects. Below, we'll explain "objects" from the inside out, following six code snippets.


1. Everything Is an Object? First, Distinguish Data Types

It's often said in JS that "everything is an object." This isn't entirely accurate, but it shows the importance of objects. Let's look at the official classification:

Category Types
Primitive data types (7) Number, String, Boolean, Null, Undefined, Symbol, BigInt
Reference data types Object (including {}, [], function () {})

The difference lies in "what the variable actually stores":

The first code snippet illustrates this:

let a = 'hello'
let b = 'hello'
console.log(a === b)   // true — the two strings have the same value

let c = Symbol('a')
let d = Symbol('a')
console.log(c === d)   // false — every Symbol is unique

The string 'hello' is a primitive type; equal values are equal. Symbol('a') may have the same description, but each Symbol is brand new and unique, so they are not equal.

Remember this classification; all the "pitfalls" that follow come from here.


2. Object = a Collection of Key-Value Pairs

An array is an ordered linear collection where each element has a unique index; an object is a collection of key-value pairs, where each value has a name (key).

Look at the second code snippet:

let obj = {          // Create an object literal
  name: '张三',
  age: 18,
}

obj.girlfriend = '小红'   // Add a property
obj.age = 20              // Modify a property

delete obj.girlfriend     // Delete a property

let a = 'hello'
obj[a] = 'world'          // Use a variable's value as the property name

console.log(obj)

The final result is:

{ name: '张三', age: 20, hello: 'world' }

With just a few lines, we've used the object's add, delete, modify, and query operations:

Operation Syntax
Read obj.name
Add obj.key = value (when the key doesn't exist)
Modify obj.key = newValue (when the key already exists)
Delete delete obj.key

Why is obj[a] equal to hello?

Because the content inside square brackets is evaluated as an expression; the value of a is 'hello', so it's equivalent to obj['hello'] = 'world'.

The distinction between the two ways is simple:

obj.name      // Find a property named name
obj[a]        // Use the value of variable a as the property name

If the property name is a variable, you must use square brackets; dot syntax won't work.

Another detail: the keys of an object are essentially strings (except Symbols); numeric keys are also converted to strings, so obj[1] and obj['1'] access the same key.

Also note: objects are reference types; the obj variable stores only an address, and the actual data resides in heap memory.


3. Creating Objects: Literal vs new

The most common syntax is the curly braces above, called an object literal.

The end of the third code snippet also demonstrates another way:

let obj = new Object()   // {}
let arr = new Array()    // []

new Object() is exactly the same as {}, just more verbose, and is rarely used in practice. But this new is crucial; it's the key to understanding constructors and prototypes.

Also remember: arrays are objects too. new Array() creates an object, just one with special behavior (ordered, has length, can be accessed by index).


4. Batch Creation: Constructor + new

Suppose you need to create objects for three cars. Writing them by hand three times (the commented-out part of the third code snippet):

let car1 = { name: 'su7', height: 1400, weight: 1500, lang: 4800, color: 'red' }
let car2 = { name: 'su7', height: 1400, weight: 1500, lang: 4800, color: 'blue' }
let car3 = { name: 'su7', height: 1400, weight: 1500, lang: 4800, color: 'green' }

That's repetitive. This is when you should use a constructor:

function Car(color) {
  this.name = 'su7'
  this.height = 1400
  this.weight = 1500
  this.lang = 4800
  this.color = color
}

let car1 = new Car('red')
let car2 = new Car('blue')
let car3 = new Car('green')

console.log(car1)   // Car { name: 'su7', height: 1400, ..., color: 'red' }

Remember three sentences about constructors:

  1. A constructor is simply a function called with new, conventionally capitalized.
  2. Its purpose is to batch-create object instances with the same structure.
  3. If you call it without new, this no longer points to the new object, and the result is wrong.

What does new actually do for you?

When executing new Car('red'), JS quietly does four things:

① Create an empty object {}
② Point the empty object's __proto__ to the constructor's prototype (the prototype link, detailed in the next section)
③ Assign this empty object to `this`, execute the function body (attach properties to `this`)
④ Return this object

Small detail: If the constructor returns an object, that returned object is used; if it returns a primitive or nothing, the newly created object is returned.

So this.name = 'su7' is just adding properties to the new object, and the result is { name: 'su7', ..., color: 'red' }.

Native functions work the same way; new Object() and new Array() are official constructors provided by JS, specifically for creating instances of the corresponding types.


5. prototype and proto: The Lookup Chain Behind Objects

The car example above has a hidden issue: if you add a method to Car, each instance will have its own copy of the function, wasting memory. To understand the solution and principle, you first need to know two properties.

Two Properties That Exist by Default

function Car() {}          // Every function has a prototype by default, and it's an object
const obj = {}             // Every object has a __proto__ by default, and it points to an object

Note the wording: prototype belongs to functions, __proto__ belongs to objects.

The Core Equation

console.log(car1.__proto__ === Car.prototype)   // true

In one sentence:

The instance's implicit prototype === the constructor's explicit prototype

This is exactly what step ② of the new four steps does: when creating an instance, the engine connects the instance's __proto__ to the constructor's prototype, so all instances share the same prototype object.

Modern syntax tip: __proto__ is a historical accessor (only standardized in Annex B in browser environments); in production code, use Object.getPrototypeOf instead:

Object.getPrototypeOf(car1) === Car.prototype   // true, recommended
car1.__proto__ === Car.prototype                // true, works but it's the old syntax

Attaching Methods to the Prototype

The fourth code snippet demonstrates this usage:

function Car(color) {
  this.name = 'su7'
  this.color = color
}

Car.prototype.push = function () {
  console.log('push executed')
}

let car1 = new Car('red')
console.log(car1.__proto__ === Car.prototype)   // true

car1.push()   // push executed

car1 doesn't have push on itself, so why can it be called? Because the engine moves up the prototype chain to find it.

What Does the Prototype Chain Look Like?

A one-line diagram:

car1  ──__proto__──▶  Car.prototype  ──__proto__──▶  Object.prototype  ──__proto__──▶  null
        Own properties        └─ push()              └─ toString / hasOwnProperty ...

V8's Lookup Rules

When the engine accesses an object's property:

First look at the object itself  →  Not found  →  Look at __proto__  →  Still not found, keep going up  →  Until null

This chain that goes up continuously is the prototype chain. When it reaches null and still hasn't found the property, the result is undefined.

How do you distinguish whether a property is "own" or "borrowed from the prototype"? Use hasOwnProperty:

car1.hasOwnProperty('name')   // true  — own
car1.hasOwnProperty('push')   // false — on the prototype

Why Can Arrays Use push?

The comment at the start of the fourth code snippet explains this:

let arr = []   // Equivalent to new Array()
arr.push(1)

console.log(arr.__proto__ === Array.prototype)   // true

arr doesn't have push on itself, but Array.prototype does, so it finds it along the prototype chain. Similarly, str.toUpperCase(), [].map() all work this way.

Why Put Methods on the Prototype?

Because "properties in the constructor" are unique to each instance, while "properties on the prototype" are shared by all instances:

function Person(name) {
  this.name = name
}
Person.prototype.sayHi = function () {
  console.log('我是' + this.name)
}

const p1 = new Person('小明')
const p2 = new Person('小红')

console.log(p1.sayHi === p2.sayHi)   // true — the same function, saves memory

this still correctly points to each respective object because this points to whoever calls it.


6. Wrapper Classes: Why str.a Can't Be Retrieved

Back to the question at the beginning:

var str = 'hello'  // Equivalent to new String('hello')
str.a = 2          // Add property a to the string object
console.log(str.a)      // undefined
console.log(str.length) // 5

Primitive types cannot have properties or methods added. So why doesn't it throw an error?

First, Clarify a Misconception

With let str = 'hello', V8 does not actually run new String('hello'); str stores a primitive string. The wrapping only happens at the moment you access a property or method, and it's temporary.

The Complete Process in V8

  1. When you write str.a = 2, V8 temporarily creates new String('hello'), obtaining a wrapper object. Inside it is a [[PrimitiveValue]] slot storing the original value 'hello'.
  2. It attaches a = 2 to this temporary wrapper object.
  3. When the statement ends, the temporary wrapper object is immediately destroyed (unboxed). The variable str still points to the primitive string — it isn't truly executing delete str.a; that object simply no longer exists.
  4. The next time you read str.a, the engine creates a brand new temporary wrapper object, which naturally lacks a — you get undefined.

Try it with a number, and it behaves exactly the same:

const n = 123       // new Number(123)
n.a = 2             // Attached to a temporary Number object, then the object is destroyed
console.log(n)      // 123
console.log(n.a)    // undefined

This is the wrapper class: to make it easy to operate on primitives, JS temporarily wraps them into objects when accessing properties, then unboxes them immediately after the operation.

Then Why Does str.length Have a Value?

Because the wrapper object's [[PrimitiveValue]] corresponds to the string content, and the wrapper object naturally has length:

console.log('hello'.length)   // 5

Similarly, 'hello'.toUpperCase() finds the method on String.prototype after temporary wrapping — this is why primitives can "call methods," but the methods aren't actually attached to the primitive value itself.

Common wrapper objects:

Primitive type Wrapper object
String / Number / Boolean new String() / new Number() / new Boolean()
Symbol / BigInt Can't use new; only Object(sym) for wrapping

Note: The silent failure described above occurs in non-strict mode; in strict mode, adding a property to a primitive throws TypeError: Cannot create property ....

One Sentence to Remember

Primitive types merely "borrow" object capabilities; they return them immediately and leave nothing behind.


7. A Final Table

Knowledge Point Key Conclusion
Data types 7 primitive types compare by value; Object / Array / Function are reference types compared by address
Creating objects {} is most common; new Object() is equivalent but rarely used
Add, delete, modify, query obj.key = value, delete obj.key, obj[key] (square brackets when key is a variable)
Constructor A function called with new, capitalized, used for batch creating instances
Four steps of new Create empty object → connect __proto__ → bind this and execute function → return object
prototype The explicit prototype that functions have by default
proto The implicit prototype that objects have by default; modern replacement: Object.getPrototypeOf()
Core equation instance.__proto__ === constructor.prototype
Prototype chain lookup First check itself, then follow __proto__ upward until null; hasOwnProperty checks whether it's own
Arrays Also objects; arr.__proto__ === Array.prototype
Wrapper classes Temporary wrapping on property access, immediate unboxing; primitives can't retain custom properties

Final Thoughts

The difficulty of objects lies not in syntax but in two "invisible" things:

Once you understand these two points, you won't be confused about why str.a is undefined, why car1.push works, and why a === b is sometimes true and sometimes false.

Finally, emphasize again: Type out each of the six code snippets in the article, change a few values, and run them. That's more effective than reading ten articles.