← Back to JavaScript, page 5

javascript-0095 · Hard senior

What does each of these class, this, and prototype puzzles print, and why?

Seven classic traps: a base constructor calling an overridden method before the subclass fields exist, a detached method losing this, arrow class fields binding this per instance, replacing a prototype object versus editing it, an inherited accessor without a setter blocking assignment, static methods using this as the calling class, and the constructor property being lost after replacing a prototype. Each follows from the lookup rules for this and the prototype chain.

Full answer

Puzzle 1. A base constructor runs before the subclass fields are initialized. If Base calls this.label() and Child overrides label to read a class field, the field is still undefined at that moment, because fields of a derived class are set right after super() returns. The method override is already visible, since methods live on the prototype from the start.

Puzzle 2. const f = obj.method loses the receiver. In strict code and in classes, this is undefined, so f() throws a TypeError when it reads a property. An arrow function stored in a class field avoids this, because the field initializer runs once per instance and the arrow captures that instance. The cost is one function object per instance, and the method is not on the prototype.

Puzzle 3. Editing Person.prototype.greet after creating instances affects them all, because they look the method up on the shared object when called. Assigning a new object, Person.prototype = {...}, affects only instances created afterward. Earlier instances keep a link to the old prototype object, so before instanceof Person becomes false, because instanceof checks the current Person.prototype.

Puzzle 4. If a prototype defines a getter without a setter, assigning that name on an instance does not create an own property. In sloppy mode the assignment is silently ignored, and in strict mode it throws a TypeError. By contrast, assigning to an inherited plain data property creates an own property that shadows it.

Puzzle 5. A static method is called with the class as this. Child.create() inherited from Base therefore creates a Child if it uses new this(), but a Base if it hard-codes new Base().

Puzzle 6. When you replace a function's prototype with an object literal, the new object has no own constructor, so instance.constructor falls back to Object. Restore it with constructor: Person in the literal or Object.defineProperty.

Puzzle 7. super.method() inside an object literal method uses the object's prototype, set with Object.setPrototypeOf, and it still passes the current this, so the parent method sees the child's data.

The common rule behind all of them: this is decided by how a function is called, and property reads walk the prototype chain at the time of the read.

javascript
'use strict';

// 1. Base constructor calls an overridden method
class Base {
  constructor() {
    this.described = this.label();
  }
  label() {
    return 'base';
  }
}
class Child extends Base {
  suffix = '!';
  label() {
    return 'child' + this.suffix;
  }
}
console.log('1:', new Child().described);

// 2. Detached method versus arrow field
class Counter {
  count = 0;
  incrementMethod() {
    return ++this.count;
  }
  incrementArrow = () => ++this.count;
}
const counter = new Counter();
const { incrementMethod, incrementArrow } = counter;
console.log('2 arrow:', incrementArrow());
try {
  incrementMethod();
} catch (error) {
  console.log('2 method:', error.constructor.name);
}
console.log('2 methods on prototype:', Object.hasOwn(counter, 'incrementMethod'), Object.hasOwn(counter, 'incrementArrow'));

// 3. Edit versus replace the prototype
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return 'hello ' + this.name;
};
const before = new Person('Asha');
Person.prototype.greet = function () {
  return 'hi ' + this.name;
};
console.log('3 edited:', before.greet());
Person.prototype = {
  greet() {
    return 'hey ' + this.name;
  },
};
const after = new Person('Ben');
console.log('3 replaced:', before.greet(), '|', after.greet());
console.log('3 instanceof:', before instanceof Person, after instanceof Person);

// 4. Inherited accessor without a setter versus a data property
class Temperature {
  get unit() {
    return 'C';
  }
}
Temperature.prototype.scale = 'metric';
const t = new Temperature();
try {
  t.unit = 'F';
} catch (error) {
  console.log('4 accessor assignment:', error.constructor.name);
}
t.scale = 'imperial';
console.log('4 data property:', t.scale, Temperature.prototype.scale, Object.hasOwn(t, 'scale'));

// 5. Static this
class Shape {
  static create() {
    return new this();
  }
  static createFixed() {
    return new Shape();
  }
}
class Circle extends Shape {}
console.log('5:', Circle.create().constructor.name, Circle.createFixed().constructor.name);

// 6. Lost constructor
function Car() {}
Car.prototype = { drive() {} };
console.log('6:', new Car().constructor === Object, new Car().constructor === Car);
Car.prototype = { constructor: Car, drive() {} };
console.log('6 fixed:', new Car().constructor === Car);

// 7. super in an object literal
const parent = {
  describe() {
    return 'parent sees ' + this.name;
  },
};
const kid = {
  name: 'kid',
  describe() {
    return super.describe() + ' via kid';
  },
};
Object.setPrototypeOf(kid, parent);
console.log('7:', kid.describe());

Run with Node.js v24.22.1 as js-95.js; two runs gave identical output. Output: 1: childundefined 2 arrow: 1 2 method: TypeError 2 methods on prototype: false true 3 edited: hi Asha 3 replaced: hi Asha | hey Ben 3 instanceof: false true 4 accessor assignment: TypeError 4 data property: imperial metric true 5: Circle Shape 6: true false 6 fixed: true 7: parent sees kid via kid

Key points

  • Derived-class fields are initialized after super() returns, so a base constructor sees them as undefined.
  • A detached method loses this; an arrow class field binds this per instance.
  • Editing a prototype affects existing instances; replacing the prototype object does not.
  • An inherited getter without a setter blocks assignment (silent in sloppy mode, TypeError in strict mode).
  • Static methods get the calling class as this, and a replaced prototype loses its constructor property.

Common mistakes

  • Calling an overridable method from a base constructor and relying on subclass state.
  • Passing obj.method as a callback without bind or an arrow wrapper.
  • Replacing Person.prototype with a literal and forgetting the constructor property.
  • Assuming that assigning to an inherited accessor creates an own property.

Follow-ups

  • Why are class fields of a derived class initialized after the super call and not before?
  • What are the memory and testing trade-offs of arrow functions as class fields?
  • How would you make a property on a prototype writable per instance when it was defined as an accessor?

Tips

  • Walk through each puzzle by naming the rule first: call-site this, or prototype lookup at read time.
  • Mention the one-function-per-instance cost of arrow fields.
  • State what changes between strict and sloppy mode for puzzle 4.