Courses / Frontend System Design, with JavaScript Foundations / Chapter 3
Module 2 · JavaScript Foundations · Chapter 3 of 21
this, Prototypes and Classes
Builds on Values, Coercion, Scope and Closures. Next up: Promises, Async Code and the Browser Event Loop.
Part 1 · The four binding rules
What this is
Inside a function, this is decided by how the function is called, not by where it is written. That one fact explains most this bugs.
Four rules decide this for an ordinary function, and a fifth case, the arrow function, opts out of them. The table lists each rule with the call that triggers it.
| Rule | Call site | this is |
|---|---|---|
| Default | f() | undefined in strict code, globalThis in sloppy code |
| Implicit | obj.f() | The object before the dot |
| Explicit | f.call(o), f.apply(o), f.bind(o)() | The object you pass |
| new | new F() | A fresh object created for the call |
| Arrow | () => {} | The this of the surrounding code, fixed when the arrow is created |
call runs the function at once with a chosen this and arguments listed one by one. apply does the same with the arguments in an array. bind does not run anything: it returns a new function with this fixed. Run each rule once.
function show() { return this === undefined ? 'undefined' : typeof this } console.log('plain call:', show()) const user = { name: 'Meera', hello() { return this.name }, } console.log('method call:', user.hello()) function greet(greeting) { return greeting + ', ' + this.name } console.log('call:', greet.call({ name: 'Kabir' }, 'Hi')) console.log('apply:', greet.apply({ name: 'Isha' }, ['Hello'])) const bound = greet.bind({ name: 'Dev' }) console.log('bind:', bound('Hey')) function Point(x) { this.x = x } const pt = new Point(3) console.log('new:', pt.x, pt instanceof Point)
One call for each rule
Reading a call site
To find this, ignore where the function was defined and look only at the call. The scene runs through four calls in one strict module and shows which rule won.
Watch for how the shape of the call, not the function, decides this
Read it as steps
Each call site is checked once; the syntax of the call picks the rule.
Four call shapes, four rules, four different values of this, in the same order as the run above. Only the plain call was a problem, since it left this as undefined. The next lesson is about how code ends up in that position by accident.
Strict code, sloppy code and collisions
The default rule depends on strict mode. ES modules and class bodies are always strict; a plain script or a CommonJS file in Node is sloppy unless it opts in with "use strict". The CommonJS file below was run with Node, since a module would always be strict.
function show() { return this === globalThis ? 'globalThis' : typeof this } console.log('plain call, sloppy:', show()) function showStrict() { 'use strict' return this === undefined ? 'undefined' : typeof this } console.log('plain call, strict:', showStrict()) var leaked = 1 function readLeak() { return this.leaked } console.log('var at top of a CommonJS file:', readLeak()) globalThis.viaGlobal = 'seen' function readGlobal() { return this.viaGlobal } console.log('property on globalThis:', readGlobal())
Default binding in a sloppy file
plain call, sloppy: globalThis plain call, strict: undefined var at top of a CommonJS file: undefined property on globalThis: seen
Output (Node 24, CommonJS file)
In sloppy code the plain call gets globalThis, so a function that writes this.x quietly creates a global. The var at the top of a CommonJS file did not become a property of globalThis, because the file is wrapped in a function by Node; a script in a browser page would behave differently. Strict code turns the whole accident into an error, which is why you want it.
When two rules could apply, the order is fixed: new beats bind, bind beats an object before the dot, and that beats the default.
function who() { return this && this.id } const a = { id: 'a', who } const b = { id: 'b', who } console.log(a.who(), b.who()) console.log(a.who.call(b)) const bound = who.bind({ id: 'bound' }) const holder = { id: 'holder', bound } console.log(holder.bound()) console.log(bound.call({ id: 'call' })) function Thing() { this.v = this && this.id } const BoundThing = Thing.bind({ id: 'bound' }) const t = new BoundThing() console.log(t.v, t instanceof Thing)
Collisions between rules
a b b bound bound undefined true
Output (Node 24)
Read the output line by line. The same function printed a and b for the two objects it was called on. Call with an explicit object gave b. A bound function stayed bound to bound even when called as a method of holder, and call could not change it. The last line printed undefined true: with new, this was the new object, which has no id, and the bound object was ignored.
Part 2 · Losing this and arrow functions
Extracted methods
The most common this bug is a method that is separated from its object. cart.count() has a dot, so this is cart. Copy the method into a variable and call it, and the dot is gone.
class Cart { items = ['pen'] count() { return this.items.length } } const cart = new Cart() console.log(cart.count()) const detached = cart.count try { detached() } catch (e) { console.log(e.constructor.name + ': ' + e.message) } setTimeout(cart.count, 0) process.on('uncaughtException', (e) => { console.log('timer: ' + e.constructor.name + ': ' + e.message) }) console.log([1, 2].map(cart.count, cart)) const fixed = cart.count.bind(cart) console.log(fixed())
Three ways to lose this
1 TypeError: Cannot read properties of undefined (reading 'items') [ 1, 1 ] 1 timer: TypeError: Cannot read properties of undefined (reading 'length')
Output (Node 24)
The first call returns 1. The detached call detached() is a plain call, and because class bodies are strict, this is undefined, so reading this.items throws. Passing the method to setTimeout loses it as well: the timer calls the function itself, and in Node the value of this there is the timer object, which has no items. That is why the message is about length, not about undefined itself. The exact value of this in a timer callback is not something to rely on.
The map call passed cart as a second argument, the thisArg that many array methods accept, and the bind call produced a new function fixed to cart. Both worked. A third option is a wrapper arrow function, covered next.
Arrow functions
An arrow function has no this of its own. When the arrow is created it captures the this of the code around it, the same way it captures any variable. Nothing about the call changes that.
const timer = { label: 'timer', startFn() { return [1].map(function () { return this }) }, startArrow() { return [1].map(() => this.label) }, } console.log(timer.startFn()) console.log(timer.startArrow()) const arrow = () => typeof this console.log(arrow.call({ a: 1 }), arrow.bind({ a: 1 })()) const obj = { name: 'obj', viaMethod() { return this.name }, viaArrow: () => this === undefined, } console.log(obj.viaMethod(), obj.viaArrow()) function f() { return this.n } const once = f.bind({ n: 1 }) const twice = once.bind({ n: 2 }) console.log(twice())
Arrows capture this; bind cannot change them
[ undefined ] [ 'timer' ] undefined undefined obj true 1
Output (Node 24)
Compare the first two lines. Inside startFn, an ordinary callback has its own this, and map calls it with none, so it saw undefined. The arrow in startArrow used the this of the method, which is the object, and returned "timer". This is the main reason arrows exist: callbacks inside methods can reach the object.
The same property causes the opposite bug when an arrow is used as an object method. viaArrow took this from the module top level, where it is undefined, so this === undefined printed true, while viaMethod returned obj. Use method syntax for methods. Arrows also ignore call, apply and bind: arrow.call(...) and arrow.bind(...)() both printed the same value. And a bound function cannot be bound again: twice() printed 1, the first binding. Both arrows saw undefined because this at the top level of an ES module is undefined.
this in event listeners
Event listeners add a twist. When the browser calls a listener written as a regular function, it sets this to the element the listener is attached to, the same object as event.currentTarget. That is different from event.target, which is the element that was actually clicked. The page below attaches five listeners and clicks the button once.
window.log = [] const go = document.getElementById('go') const box = document.getElementById('box') class Cart { name = 'cart' onClick() { log.push('method: this is ' + this.tagName) } onClickArrow = () => { log.push('arrow field: this is ' + this.name) } } const cart = new Cart() go.addEventListener('click', cart.onClick) go.addEventListener('click', cart.onClickArrow) go.addEventListener('click', function (e) { const same = this === e.currentTarget log.push('function: this === currentTarget ' + same) }) box.addEventListener('click', function (e) { log.push('on box: this is ' + this.id) log.push('on box: target is ' + e.target.id) }) go.addEventListener('click', () => { log.push('arrow: this is window ' + (this === window)) })
The page script: listeners in Chrome 157, clicked by Playwright
Chrome/157.0.0.0 method: this is BUTTON arrow field: this is cart function: this === currentTarget true arrow: this is window true on box: this is box on box: target is go
Output (Chrome 157)
The class method used as a listener got the button as this, not the cart, so this.name would have been undefined. The arrow field kept the cart. A function listener saw currentTarget. The arrow written at the top of the page took the page's this, which is window. And the listener on the outer box saw this as the box while target was the button, because the click bubbled up from the button to the box.
Why does const run = cart.count; run() fail in a class method?
- The call is a plain call with no object before the dot, and class code is strict, so
thisisundefined. - Fix it with
bind, an arrow wrapper, or by callingcart.count().
How does an arrow function decide this?
- It takes
thisfrom the surrounding code where the arrow was created.call,applyandbindcannot change it.
Part 3 · The prototype chain
Looking up a property
Every object has an internal link to another object or to null, called its prototype. When you read a property, the engine looks at the object, then at its prototype, then at that object's prototype, and so on until it finds the name or reaches the end of the chain. This is how objects share behaviour without copying it.
Object.create(proto) makes an object whose prototype is proto. Object.getPrototypeOf(o) reads the link. Prefer these to the older __proto__ accessor. Object.hasOwn(o, key) asks whether a property belongs to the object itself, not to something it inherits.
const animal = { legs: 4, describe() { return this.name + ' has ' + this.legs + ' legs' }, } const dog = Object.create(animal) dog.name = 'Bruno' console.log(dog.describe()) console.log(Object.getPrototypeOf(dog) === animal) console.log(Object.hasOwn(dog, 'name'), Object.hasOwn(dog, 'legs')) console.log('legs' in dog, dog.legs) console.log(Object.keys(dog), JSON.stringify(dog)) for (const key in dog) console.log('for...in:', key) dog.legs = 3 console.log(dog.legs, animal.legs, Object.hasOwn(dog, 'legs')) delete dog.legs console.log(dog.legs) console.log(Object.getPrototypeOf(animal) === Object.prototype) console.log(Object.getPrototypeOf(Object.prototype)) const bare = Object.create(null) bare.x = 1 console.log('toString' in bare, 'toString' in {})
Own, inherited and shadowed properties
Bruno has 4 legs true true false true 4 [ 'name' ] {"name":"Bruno"} for...in: name for...in: legs for...in: describe 3 4 true 4 true null false true
Output (Node 24)
Only name is the dog's own. The in operator and a for...in loop include inherited properties, which is why the loop printed legs and describe too. Object.keys and JSON.stringify see only own properties. Inside describe, the implicit rule from the first lesson applies: it was called as dog.describe(), so this is the dog, and the method found on animal read the dog's own name.
Writing, shadowing and the end of the chain
Reading walks the chain, but writing does not. Assigning to a property creates or updates an own property on the object you assigned to, even if the name exists further up.
In the second half of the file, after dog.legs = 3, the dog read 3, the shared animal still held 4, and hasOwn was true. Deleting the own property made the inherited value visible again, 4. The chain ends: animal's prototype is Object.prototype, whose prototype is null. An object made by Object.create(null) has no prototype at all, so it has no toString, which makes it a clean dictionary. The final line printed false true for "toString" in bare and "toString" in {}.
Chains made by classes and constructors
The objects you meet in practice have longer chains. An instance of a class has the class's prototype object as its prototype, and that object has the parent class's prototype object as its prototype. The scene follows the lookup for five names on one object.
class Animal { speak() { return this.name + ' makes a sound' } } class Dog extends Animal { constructor(name) { super(); this.name = name } fetch() { return this.name + ' fetches' } } const d = new Dog('Bruno') function owner(obj, key) { const names = new Map([ [d, 'instance'], [Dog.prototype, 'Dog.prototype'], [Animal.prototype, 'Animal.prototype'], [Object.prototype, 'Object.prototype'], ]) for (let o = obj; o !== null; o = Object.getPrototypeOf(o)) { if (Object.hasOwn(o, key)) return names.get(o) } return 'not found' } for (const key of ['name', 'fetch', 'speak', 'toString', 'nope']) { console.log(key.padEnd(9), owner(d, key)) }
Where each name is found
name is an own property of the dog instance
Read it as steps
A lookup climbs one link at a time until the name is found.
name instance fetch Dog.prototype speak Animal.prototype toString Object.prototype nope not found
Output (Node 24)
In the scene, inst is the dog, Cls is Dog.prototype, Par is Animal.prototype and Obj is Object.prototype, and the output above gives the same owner for each name. The instance holds only its data, name. Every method lives once on a shared prototype, and each class level adds one link to walk. A name that no object owns walks the whole chain to null; a plain read such as d.nope then gives undefined rather than an error, which is why a misspelt property name fails quietly.
Methods shared through a constructor
Before the class keyword, you built the same structure by hand. A constructor function plus assignments to its prototype property did the job. new Counter() makes an object whose prototype is Counter.prototype.
function Counter() { this.n = 0 } Counter.prototype.inc = function () { this.n += 1 } const a = new Counter() const b = new Counter() console.log(a.inc === b.inc, a.hasOwnProperty('inc')) console.log(Object.getPrototypeOf(a) === Counter.prototype) console.log(a.constructor === Counter) Counter.prototype.reset = function () { this.n = 0 } a.inc() a.reset() console.log(a.n, typeof b.reset) const list = [3, 1, 2] console.log(Object.getPrototypeOf(list) === Array.prototype) console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype) const shared = { tags: [] } const x = Object.create(shared) const y = Object.create(shared) x.tags.push('hot') console.log(y.tags)
One function shared by every instance
true false true true 0 function true true [ 'hot' ]
Output (Node 24)
The two counters share one inc function (true) that is not an own property (false). Adding reset to the prototype later made it available to instances that already existed. The lesson has a warning too. The last lines created two objects from one shared prototype. Pushing to x.tags changed the array that y.tags also sees, because there is only one array, on the prototype. Put mutable per-instance data on the instance, in the constructor, never on a shared prototype.
obj.name = 1 and name exists on the prototype. What happens to the prototype?
- Nothing. The assignment creates an own property on
objthat shadows the inherited one.
What do Object.keys, in and for...in each include?
Object.keyslists own enumerable properties only.inandfor...inalso include inherited ones.
Why is an array on a shared prototype a bug?
- All instances reach the same array, so one instance's push shows in every other, as
y.tagsshowed.
Part 4 · What class creates
A function with a prototype
The class keyword is syntax over prototypes, with extra rules. A class declaration creates a function, the constructor, and an object on its prototype property that holds the methods. Instances get that object as their prototype.
class Account { static count = 0 static { Account.bank = 'Example Bank' } owner balance = 0 constructor(owner) { this.owner = owner Account.count += 1 } deposit(amount) { this.balance += amount return this } get summary() { return this.owner + ': ' + this.balance } } console.log(typeof Account, Account.name) console.log(Object.getOwnPropertyNames(Account.prototype)) console.log(Object.keys(Account.prototype)) const acc = new Account('Tara').deposit(500) console.log(acc.summary, Object.keys(acc)) console.log(Account.count, Account.bank) try { Account('Ravi') } catch (e) { console.log(e.constructor.name + ': ' + e.message) } console.log(Object.getPrototypeOf(acc) === Account.prototype) console.log(Account.prototype.constructor === Account)
What a class declaration creates
function Account [ 'constructor', 'deposit', 'summary' ] [] Tara: 500 [ 'owner', 'balance' ] 1 Example Bank TypeError: Class constructor Account cannot be invoked without 'new' true true
Output (Node 24)
typeof Account is "function". The methods and the getter live on Account.prototype, shared by every instance, and Object.keys shows none of them because class methods are not enumerable. Fields declared in the body, owner and balance, are own properties of each instance. static members belong to the class itself, and a static block runs once when the class is defined, which suits setup that needs a statement.
A class cannot be called without new: the error reads Class constructor Account cannot be invoked without 'new'. A plain constructor function can be called wrongly and silently pollute this; a class stops you.
Differences from constructor functions
A few rules make classes safer than the hand-written pattern.
- The body is always strict, so an extracted method gets
undefinedforthis, not the global object. - Class declarations are not usable before their line, like
let. Function declarations are hoisted whole. - Methods are non-enumerable, so they do not show up in
for...in. - The constructor must be called with
new.
try { new Late() } catch (e) { console.log(e.constructor.name + ': ' + e.message) } class Late {} function Early() {} console.log(typeof new Early()) const proto = Object.getOwnPropertyDescriptor( class A { m() {} }.prototype, 'm', ) console.log(proto.enumerable, proto.writable)
A class in its dead zone
ReferenceError: Cannot access 'Late' before initialization
object
false trueOutput (Node 24)
Using Late above its declaration threw the same kind of error as let. The plain function Early could be called with new anywhere. The last line shows that a class method is writable but not enumerable: false true.
Fields, arrow fields and initialisation order
A class field with an arrow function, such as handleField = () => this.label, is a common fix for the lost this problem. It works because the field initialiser runs inside the constructor, where this is the new instance, and the arrow captures it. The price is that each instance gets its own copy of the function, instead of sharing one from the prototype.
class Button { label = 'ok' handleField = () => this.label handleMethod() { return this.label } } const a = new Button() const b = new Button() console.log(a.handleMethod === b.handleMethod) console.log(a.handleField === b.handleField) console.log(Object.keys(a)) const { handleField, handleMethod } = a console.log(handleField()) try { handleMethod() } catch (e) { console.log(e.constructor.name) } class Base { id = 'base-field' constructor() { console.log('Base sees', this.id, this.tag) } } class Child extends Base { tag = 'child-field' } const c = new Child() console.log(c.id, c.tag)
Arrow fields, methods and the order of initialisation
true false [ 'label', 'handleField' ] ok TypeError Base sees base-field undefined base-field child-field
Output (Node 24)
The method is shared (true) and the arrow field is not (false). The arrow field is an own property, so it appears in Object.keys. The destructured arrow still worked, ok, while the destructured method failed with a TypeError. For a handful of components this cost is nothing; for thousands of instances, prefer a method and bind or wrap it where you pass it.
The last lines show initialisation order. In a base class, fields are set before the constructor body runs. In a subclass, fields are set right after super() returns. So the parent constructor saw its own id but not the child's tag, which printed undefined. Avoid calling overridable methods from a constructor for the same reason.
extends and super
class Dog extends Animal sets up two links. Dog.prototype's prototype becomes Animal.prototype, so instances can reach inherited methods, and Dog's own prototype becomes Animal, so static members are inherited too. Inside a subclass, super.method() calls the parent's version.
class Shape { constructor(name) { this.name = name } describe() { return 'shape ' + this.name } } class Square extends Shape { constructor(side) { super('square') this.side = side } describe() { return super.describe() + ' of side ' + this.side } } const s = new Square(4) console.log(s.describe()) console.log(Object.getPrototypeOf(Square) === Shape) console.log(Object.getPrototypeOf(Square.prototype) === Shape.prototype) console.log(s instanceof Square, s instanceof Shape)
A subclass
const show = (e) => { const msg = e.message.replace(' or ', '\n or ') console.log(e.constructor.name + ':\n ' + msg) } class Bad extends Shape { constructor() { this.x = 1 super('bad') } } try { new Bad() } catch (e) { show(e) } class Lazy extends Shape { constructor() {} } try { new Lazy() } catch (e) { show(e) } const extract = s.describe try { extract() } catch (e) { show(e) }
Two ways to misuse super, and an extracted method (show wraps messages)
shape square of side 4 true true true true ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor TypeError: Cannot read properties of undefined (reading 'name')
Output (Node 24)
In a derived class constructor, this does not exist until super() has run, because the parent constructor creates the object. Touching this first, or never calling super(), throws a ReferenceError whose message is printed above. The last error is the extracted-method bug from the second lesson, now in a subclass: the call has no dot, the code is strict, and this is undefined.
Where do the methods of a class live, and are they enumerable?
- On
Class.prototype, shared by all instances. They are not enumerable, soObject.keysdoes not list them.
Part 5 · Private fields and composition
Private fields
A field or method name that starts with # is private. It exists only inside the class body. The name is part of the syntax, not a string key, so code outside cannot reach it: writing w.#paise outside the class does not even run, and Node rejects the file with SyntaxError: Private field '#paise' must be declared in an enclosing class.
class Wallet { #paise = 0 static isWallet(o) { return #paise in o } add(p) { this.#paise += p } get rupees() { return this.#paise / 100 } } const w = new Wallet() w.add(2550) console.log(w.rupees, Object.keys(w), JSON.stringify(w)) console.log(w.paise, Wallet.isWallet(w), Wallet.isWallet({}))
Private state and a brand check
25.5 [] {}
undefined true falseOutput (Node 24)
The private amount is stored in paise and exposed in rupees through a getter, 25.5. Object.keys and JSON.stringify do not see it, and w.paise, a different, ordinary name, is undefined. The static method uses #paise in o, a brand check: it is true only for objects made by this class, so it tells real wallets from lookalike objects.
Private names and receivers
Private names are tied to the exact object that was constructed by the class. If a method runs with another this, the access fails. The same applies to a Proxy, which is a different object from its target.
class Wallet { #paise = 0 add(p) { this.#paise += p } get rupees() { return this.#paise / 100 } } const show = (e) => { const msg = e.message.replace(' from ', '\n from ') console.log(e.constructor.name + ':\n ' + msg) } const w = new Wallet() w.add(2550) const other = { add: w.add, rupees: 0 } try { other.add(1) } catch (e) { show(e) } const proxied = new Proxy(w, {}) try { console.log(proxied.rupees) } catch (e) { show(e) } const viaBind = new Proxy(w, { get(t, k) { const v = Reflect.get(t, k, t) return typeof v === 'function' ? v.bind(t) : v }, }) console.log(viaBind.rupees)
The two failures and one fix
TypeError:
Cannot read private member #paise
from an object whose class did not declare it
TypeError:
Cannot read private member #paise
from an object whose class did not declare it
25.5Output (Node 24)
The first error came from calling add with other as this, an object the class never built. The second came from reading a getter through a proxy: the getter ran with the proxy as this, and the proxy does not own the private field. The fix used Reflect.get(t, k, t) to run the getter with the real target as this, and bound functions to the target, so the last line printed 25.5. A proxy around a class with private fields needs this care.
Private methods and static privates
Methods and static members can be private too. A private method is the natural home for validation that callers should not use, and a private static field holds class-wide state, such as a counter, that nobody can reset from outside.
class Money { #paise static #made = 0 constructor(paise) { this.#paise = Money.#check(paise) Money.#made += 1 } static #check(n) { if (Number.isInteger(n)) return n throw new RangeError('paise must be an integer') } equals(other) { return this.#paise === other.#paise } static get made() { return Money.#made } } console.log(new Money(500).equals(new Money(500)), Money.made) try { new Money(1.5) } catch (e) { console.log(e.name + ': ' + e.message) } try { Money.check(1) } catch (e) { console.log(e.name) }
A private static method and field
true 2
RangeError: paise must be an integer
TypeErrorOutput (Node 24)
The constructor validates through Money.#check, so a non-integer amount of paise is rejected with a RangeError before it is stored. The method equals reads other.#paise, which is allowed because code inside the class may touch the private fields of any instance of that class, not only its own this. The counter reached 2 after two valid constructions. From outside, Money.check does not exist at all, so calling it was a TypeError about a missing function, which means private names are not even visible as properties.
Composition over deep inheritance
Inheritance models "is a", and each extra level couples a child to its parent: a change to a parent method can break children that depend on it. Deep trees are hard to change. Composition builds behaviour by combining small pieces, either by copying functions into one object or by passing collaborators in.
const canFly = (s) => ({ fly: () => s.name + ' flies' }) const canSwim = (s) => ({ swim: () => s.name + ' swims' }) function makeDuck(name) { const state = { name } return { ...canFly(state), ...canSwim(state), name: () => state.name } } const duck = makeDuck('Donald') console.log(duck.fly(), duck.swim()) class Logger { log(m) { return '[log] ' + m } } class Store { constructor(logger) { this.logger = logger; this.data = new Map() } set(k, v) { this.data.set(k, v); return this.logger.log('set ' + k) } } console.log(new Store(new Logger()).set('theme', 'dark')) console.log(new Store({ log: (m) => 'fake ' + m }).set('theme', 'dark'))
Behaviours mixed in and a collaborator passed in
Donald flies Donald swims [log] set theme fake set theme
Output (Node 24)
The duck gets fly and swim from two small functions that share a state object, with no base class. Store receives its logger instead of creating one, so a test can pass a fake, as the last line does. Use extends for a real "is a" relationship with a stable parent, and use composition when you are tempted to inherit only to reuse code.
How does a private field differ from a property whose name starts with an underscore?
- A private field is enforced by the language: code outside the class cannot read it, and wrong receivers throw. An underscore is only a convention.
What does #paise in o test?
- Whether
owas constructed by the class that declares#paise. It is a brand check and does not throw.
Why did reading a getter through a Proxy throw?
- The getter ran with the proxy as
this, and the proxy does not own the private field. UsingReflect.get(target, key, target)fixes it.
All chapters · Previous: Values, Coercion, Scope and Closures