Chapter 9: Objects, prototypes, and classes
The introduction explains why JavaScript objects are more than key-value pairs and why prototypes still matter in an era of classes.
After this chapter you will be able to
- Objects beyond key-value pairs. Explain that JavaScript objects can do more than hold ordinary key-value pairs: members can have special properties, object access can be intercepted, and prototypes provide inheritance.
- Prototypes and modern classes. Distinguish the historical prominence of prototypes from the modern preference for classes, and explain why prototypes remain worth understanding.
- Customizing object property access. Explain why ordinary property assignment may not be enough and identify the property behaviors getter and setter methods can support.
- Property accessors versus named methods. Distinguish ordinary methods named with get or set prefixes from language-level getters and setters, and explain what happens when a property with accessors is read or assigned.
- Accessors on existing objects. Describe when Object.defineProperty is needed for getters and setters and how it differs from the get and set keywords.
- Property enumeration defaults. Explain why a property created with Object.defineProperty can exist but be absent from Object.keys and copied data, and how enumerable: true changes that.
- Accessor descriptor behavior. Describe what makes a descriptor an accessor descriptor and what happens when it supplies only a getter or only a setter.
- Property configurability rules. Explain how the configurable option affects whether a property definition can be changed or deleted.
- Data descriptor writability. Describe when to use a data descriptor and how its value and writable options affect assignment, including the case of a writable but non-configurable property.
- Proxy interception and fallback. Explain how a proxy controls access to a target object through a handler’s traps, and what happens when no trap handles an operation. Distinguish this object-wide interception from a getter or setter for one property.
- Inheritance and prototype foundations. Explain that inheritance reuses and organizes code by extending one object's features into another, and that JavaScript classes were built on the earlier prototype-based approach.
- Prototype chain property lookup. Trace how JavaScript searches an object and then its prototypes for a property, using yoshi, hattori, and kuma as an example.
- Own versus accessible properties. Distinguish checking whether an object can access a property from checking whether it owns that property, and describe the own-property check presented here.
- Constructor prototype inheritance. Explain what happens to an object's prototype when a function is invoked with new, and why arrow functions cannot serve as constructors.
- Dynamic prototype fallback behavior. Explain how own properties and changes to a shared prototype affect inherited values, and describe why modifying prototypes is approached cautiously.
- Classes and existing JavaScript rules. Explain that JavaScript classes operate according to the same rules as functions and prototypes, without claiming this introduction explains those rules in detail.
- Class constructors and defaults. Explain that a class succinctly defines a constructor function and a prototype, that the constructor keyword identifies the function run by new Ninja, and that an explicit constructor is optional.
- Prototype and static properties. Distinguish properties declared in a class for its instances from properties attached to the class with static.
- Class inheritance through prototypes. Explain how extends creates a parent-child relationship between classes and how an instance can use methods from both classes through prototype chaining.
- Parent access with super. Describe what super refers to and what happens when it is used in a child constructor, including the stated ordering rule for this.
- Private field syntax and scope. Explain that a field prefixed with # is private, that this syntax is available in classes rather than ordinary objects, and that referencing the field outside its class definition causes a syntax error.
What it builds on
- Type annotations and declarations (chapter 2) · TypeScript type annotations and declarations provide context for describing a variable’s type.
- Iterables and iterators (chapter 8) · The earlier introduction to symbols as object keys.
- Invocation as a constructor (chapter 6) · Invoking a function as a constructor with new.
Section by section
Introduction
The introduction explains why JavaScript objects are more than key-value pairs and why prototypes still matter in an era of classes.
- Objects beyond key-value pairs: Explain that JavaScript objects can do more than hold ordinary key-value pairs: members can have special properties, object access can be intercepted, and prototypes provide inheritance.
Why it matters: This broader view prepares you to recognize what the chapter’s object features are for. - Prototypes and modern classes: Distinguish the historical prominence of prototypes from the modern preference for classes, and explain why prototypes remain worth understanding.
Why it matters: Learning prototypes helps make sense of classes even if you usually write classes instead.
Key terms: object properties, Proxy, prototype, prototypes, classes, inheritance, TypeScript
9.1 Customizing objects with properties
The section introduces getter and setter methods as a way to customize what happens when an object property is read or written.
- Customizing object property access: Explain why ordinary property assignment may not be enough and identify the property behaviors getter and setter methods can support.
Why it matters: It explains why you might use getter and setter methods instead of treating every property as a value to read or assign directly.
Key terms: properties, skillLevel, getter and setter methods
9.1.1 Defining getters and setters
This section explains how JavaScript getters and setters make property access run methods, why that is useful, and how to add them to existing objects.
- Property accessors versus named methods: Distinguish ordinary methods named with get or set prefixes from language-level getters and setters, and explain what happens when a property with accessors is read or assigned.
Why it matters: It helps you tell a method call from property access that runs code. - Benefits of accessor properties: Explain why an API might use getters and setters instead of separate getX/setX methods.
Why it matters: A property can offer a simple interface without giving up behavior behind it. - Accessors on existing objects: Describe when Object.defineProperty is needed for getters and setters and how it differs from the get and set keywords.
Why it matters: It lets you choose the appropriate approach when the object has already been created. - TypeScript dynamic property typing: Explain why adding a property with Object.defineProperty creates a TypeScript typing choice in the example.
Why it matters: It explains why the TypeScript example needs an assertion when it adds an accessor dynamically.
Key terms: getter, setter, get, set, firstNinja, direct property access, validation, logging, internal representation, Object.defineProperty
9.1.2 Defining and redefining object properties
This section explains how Object.defineProperty descriptors control whether properties are enumerated, accessed, reassigned, or redefined.
- Property enumeration defaults: Explain why a property created with Object.defineProperty can exist but be absent from Object.keys and copied data, and how enumerable: true changes that.
Why it matters: Enumeration determines what consumers see when they list, copy, or serialize an object’s properties. - Symbol key enumeration exception: Distinguish how an enumerable symbol-keyed property behaves in loops and methods such as Object.keys from how it behaves when properties are copied.
Why it matters: Symbol keys are an exception to the usual expectation that an enumerable property appears in property listings. - Accessor descriptor behavior: Describe what makes a descriptor an accessor descriptor and what happens when it supplies only a getter or only a setter.
Why it matters: The presence or absence of accessor methods determines what reading and writing the property will do. - Property configurability rules: Explain how the configurable option affects whether a property definition can be changed or deleted.
Why it matters: Configurability concerns changes to the property definition, not simply whether its value can be assigned. - Data descriptor writability: Describe when to use a data descriptor and how its value and writable options affect assignment, including the case of a writable but non-configurable property.
Why it matters: Data descriptors let you control assignment and property-definition changes separately without using a getter for a simple value.
Key terms: Object.defineProperty, descriptor, enumerable, non-enumerable, symbol, Object.keys, Object.assign, spread syntax, accessor descriptor, get
9.2 Intercepting object access with Proxy and Reflect
This section explains how proxies intercept operations on objects, how Reflect can pass operations through, and where proxies are useful or costly.
- Proxy interception and fallback: Explain how a proxy controls access to a target object through a handler’s traps, and what happens when no trap handles an operation. Distinguish this object-wide interception from a getter or setter for one property.
Why it matters: This is the basic model for reasoning about what an operation on a proxy will do. - Reflect pass-through operations: Explain how Reflect.get and Reflect.set can pass property reads and assignments through to a proxy’s target, including the receiver’s role as the value of this.
Why it matters: Reflect lets an intercepting trap perform the corresponding operation on the target. - Range of proxy traps: Describe operations proxies can intercept beyond property reads and assignments, using the section’s named traps as examples.
Why it matters: The variety of traps explains why proxies can give objects behaviors that property definitions alone cannot. - Proxy uses and costs: Describe the section’s practical uses for proxies and explain its caution about using them in performance-critical production code.
Why it matters: The examples show when interception is valuable and when its overhead makes it a poor choice.
Key terms: Proxy, target, handler, traps, get, set, Reflect, Reflect.get, Reflect.set, receiver
9.3 Dynamic inheritance with prototypes
Introduces inheritance as a way to reuse and organize code, and identifies prototypes as the foundation of JavaScript classes.
- Inheritance and prototype foundations: Explain that inheritance reuses and organizes code by extending one object's features into another, and that JavaScript classes were built on the earlier prototype-based approach.
Why it matters: This connection explains why prototypes matter even when working with classes.
Key terms: inheritance, prototype objects, constructor functions, classes
9.3.1 Fallbacks as inheritance
This section explains how prototype chains provide fallback property access, how to set up the example chain, and how to distinguish an object's own properties from inherited ones.
- Prototype chain property lookup: Trace how JavaScript searches an object and then its prototypes for a property, using yoshi, hattori, and kuma as an example.
Why it matters: This lookup rule explains why an object can access a property it does not contain itself. - Setting an object prototype: Describe what Object.setPrototypeOf does in the example and why the section cautions against using it in production code.
Why it matters: It clarifies both how the example's links are formed and why that demonstration is not the recommended production approach. - Heritable property kinds: Explain whether prototype inheritance in JavaScript applies to data properties as well as methods.
Why it matters: It prevents treating prototype fallback as something reserved for methods. - Own versus accessible properties: Distinguish checking whether an object can access a property from checking whether it owns that property, and describe the own-property check presented here.
Why it matters: This distinction lets you tell an object's direct settings from defaults supplied by a prototype.
Key terms: prototype, prototype chain, prototype chaining, fallback, Object.setPrototypeOf, data properties, methods, inheritance, in operator, own property
9.3.2 Building prototyped objects with constructors
This section explains how constructors create objects linked to prototypes, how those prototypes can change inherited behavior, and why prototype-free objects and classes offer different trade-offs.
- Constructor prototype inheritance: Explain what happens to an object's prototype when a function is invoked with new, and why arrow functions cannot serve as constructors.
Why it matters: This link explains where constructor-created objects get inherited properties. - Prototype-free object creation: Distinguish the prototype of an object literal from an object created with Object.create(null), and describe the suggested use for a prototype-free object.
Why it matters: An empty-looking object may still inherit properties unless it is deliberately created without a prototype. - Dynamic prototype fallback behavior: Explain how own properties and changes to a shared prototype affect inherited values, and describe why modifying prototypes is approached cautiously.
Why it matters: Shared prototypes can change many objects' behavior at once, while an object's own property can hide an inherited value. - Classes and constructor typing: Describe the relationship between class syntax and constructor prototypes, and explain why TypeScript needs extra type information for the old-school constructor pattern shown here.
Why it matters: It connects constructor-based inheritance to class syntax and explains a practical reason to prefer classes in TypeScript.
Key terms: constructor, new keyword, prototype, X.prototype, arrow functions, object literal, Object.prototype, Object.create(null), prototype-free objects, key-value store
9.4 Classic OOP with class and extends
Introduces classes as JavaScript’s way to write classic object-oriented code while retaining its existing function and prototype rules.
- JavaScript’s multiple programming styles: Explain that JavaScript supports procedural, functional, and object-oriented programming, and that ES2015 classes made classic OOP possible in JavaScript.
Why it matters: Classes add an OOP style to a language that also supports other approaches. - Classes and existing JavaScript rules: Explain that JavaScript classes operate according to the same rules as functions and prototypes, without claiming this introduction explains those rules in detail.
Why it matters: This connection frames classes as part of JavaScript’s existing object model rather than a separate system.
Key terms: multi-paradigmatic, classes, ES2015, object-oriented programming (OOP), functions, prototypes
9.4.1 Classes as shorthand for prototypes
This subsection explains how class syntax defines constructors and prototype properties, and how to distinguish and inspect class instances.
- Class constructors and defaults: Explain that a class succinctly defines a constructor function and a prototype, that the constructor keyword identifies the function run by new Ninja, and that an explicit constructor is optional.
Why it matters: It connects class syntax to the constructors and prototypes it represents. - Prototype and static properties: Distinguish properties declared in a class for its instances from properties attached to the class with static.
Why it matters: It clarifies whether a class property belongs to instances through their prototype or to the class itself. - Instance checks and type checks: Distinguish what instanceof checks from the basic type reported by typeof for a class instance.
Why it matters: The two checks answer different questions about an instance. - Constructor names for debugging: Explain how an instance’s constructor property and the constructor’s name property can reveal a class name, and why that name is unreliable for production logic.
Why it matters: It gives a way to inspect an instance without treating a changeable name as a dependable program check.
Key terms: class, constructor, new, prototype, instances, static, instanceof, typeof, prototype chain, constructor property
9.4.2 Inheriting across classes
This section explains how classes inherit through prototype chaining, how super refers to a parent class, and what limits the section places on inheritance.
- Class inheritance through prototypes: Explain how extends creates a parent-child relationship between classes and how an instance can use methods from both classes through prototype chaining.
Why it matters: It connects class inheritance to the prototype chaining described earlier. - Parent access with super: Describe what super refers to and what happens when it is used in a child constructor, including the stated ordering rule for this.
Why it matters: It explains how a child constructor can invoke its parent constructor while constructing the same object. - Static property inheritance limit: State the section’s distinction between inherited instance methods and static properties.
Why it matters: It marks a limit to the inheritance behavior illustrated with instance methods. - Single-parent inheritance limit: Explain what linear inheritance means for prototypes and classes in JavaScript.
Why it matters: It sets a boundary on the parent-child relationships created with extends.
Key terms: extends, parent-child relationship, prototype chaining, super, parent class, constructor, this, static properties, linear inheritance, multiple inheritance
9.4.3 Restricting access with private elements
This section explains how class private fields restrict access, how they differ from ordinary properties, and why they are useful.
- Private field syntax and scope: Explain that a field prefixed with # is private, that this syntax is available in classes rather than ordinary objects, and that referencing the field outside its class definition causes a syntax error.
Why it matters: The # marks a class member whose access is restricted by the language. - Private field access limits: Distinguish private-field dot access from bracket access, and state that private fields cannot be proxied, enumerated, or deleted.
Why it matters: These limits explain why a private field is not just an ordinary property with an unusual name. - Uses of private fields: Describe why a class might use a private field to store an internal value for a getter/setter pair, including the clarity and autocomplete benefits of the # syntax.
Why it matters: Private fields make internal state easier to identify and keep out of external coding suggestions.
Key terms: private element syntax, private fields, class definition, dot syntax, proxied, enumerated, deleted, internal value, getter/setter pair, developer ergonomics
9.5 Summary
Where this is used later
- Maps (chapter 10) · Objects have properties accessed by keys.
- Immutable transformations with Immer (chapter 10) · Proxy can intercept interactions with an object
Concepts explained in this chapter
- prototypeA prototype is an object from which another JavaScript object can inherit properties and methods.
- classA class is JavaScript syntax for defining object construction and behavior that is implemented through the prototype system.
- Object.definePropertyObject.defineProperty is a JavaScript built-in method that creates or modifies an object's property with a specified property descriptor.
- prototype chainThe linked sequence of prototype objects used for JavaScript inheritance and property lookup.
- constructor methodA JavaScript function used to create and initialize an object, typically when invoked with the new operator.
- inheritanceInheritance is the behavior by which a JavaScript object obtains accessible properties from its prototype chain, including both data properties and methods.
- accessor descriptorAn object property whose value is accessed through getter or setter behavior rather than a directly stored value.
- getterA getter is an object or class property accessor that computes and returns a value when the property is read.
- setterA setter is a property accessor that receives a value when the property is assigned.
- ProxyProxy is a JavaScript built-in object type that mediates operations on a target object through configurable interception functions.
- trapA proxy trap is a handler function that intercepts a specific operation performed through a JavaScript proxy.
- configurable propertyA configurable property is an object property whose definition may be changed or deleted when its configurable attribute is true.
- data descriptorA data descriptor is a property descriptor that specifies a property's stored value and data-property attributes.
- enumerable propertyAn enumerable property is an object property whose enumerable attribute allows it to be included by specified property-iteration and copying operations.
- property descriptorA property descriptor is an object that specifies the attributes used to define a JavaScript property.
- read-write propertyA writable property is a data property whose stored value may be changed through assignment when its writable attribute is true.
- new keywordThe new operator invokes a constructable function, creates an object for its this value, and returns the constructed object subject to explicit-return rules.
- prototype-based object orientationPrototypal inheritance is an inheritance model in which objects obtain properties and methods through links to other objects.
- JavaScriptJavaScript is a high-level programming language standardized as ECMAScript and widely used for web and general-purpose software development.
- typeof operatorThe JavaScript typeof operator returns a string indicating the basic type of its operand.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
