Finding the Shared Methods

In the last lesson, you followed the drilling kit’s lookup from one object to the next until it reached Object.prototype and then null. The checkout app makes its kits with new, though. When KIT-17 calls describe(), which object supplies the method?

In Python, the answer is the class. In JavaScript, it’s a separate object with a misleading name. Knowing which one tells you which kits see a change to a shared method and helps you read older JavaScript.

Meet the Three Objects Behind a Kit

Here’s a cut-down Python Kit with only the kit code and describe():

Language: Python
class Kit:
    def __init__(self, code):
        self.code = code

    def describe(self):
        return f"{self.code}: tool kit"

drilling = Kit("KIT-17")
print(type(drilling) is Kit)
print("describe" in vars(Kit), "describe" in vars(drilling))

Python prints True, then True False. One object, the class Kit, is both what you call to make a kit and where describe() lives.

Older JavaScript, written before class existed, splits those roles. A constructor function is an ordinary function, written with the function keyword, that you call with new. Each one carries a .prototype property holding a plain object, where the shared methods go.

Arrow functions and shorthand methods such as a class’s describe() {} don’t have a .prototype property and can’t be called with new. A function expression stored on Kit.prototype becomes describe() for every kit:

Language: JavaScript
function Kit(code) {
  this.code = code;
}

Kit.prototype.describe = function () {
  return `${this.code}: tool kit`;
};

const drilling = new Kit("KIT-17");
const repair = new Kit("KIT-23");
console.log(drilling.describe(), repair.describe());
console.log(drilling.describe === repair.describe);
console.log(Object.hasOwn(drilling, "describe"));

Both kits describe themselves, and they use one function between them:

Language: Program Output
KIT-17: tool kit KIT-23: tool kit
true
false

The Kit function, the Kit.prototype object, and a kit instance make three objects where Python has two. When you call a function like Kit with new, JavaScript creates an empty object linked to Kit.prototype, runs Kit with that object as this, and hands the object back, unless the function explicitly returns some other object.

As with a Python class, a method added later reaches kits that already exist, because new copies nothing from Kit.prototype. The desk adds a shelf location after creating drilling:

Language: JavaScript
function Kit(code) {
  this.code = code;
}

const drilling = new Kit("KIT-17");

Kit.prototype.location = function () {
  return `${this.code} shelf A`;
};

console.log(drilling.location());

The existing kit finds the new method on its next lookup:

Language: Program Output
KIT-17 shelf A

Replacing the whole Kit.prototype object works differently, because only kits made afterward link to the new object, while existing kits keep their link to the old one and never see methods added to its replacement.

Find the Prototype of Kit Itself

The name .prototype invites a wrong reading. In Python, the class is both what made drilling and where drilling’s methods live, so a property called Kit.prototype sounds like Kit’s own prototype, the object Kit itself links to. You can test that reading with Object.getPrototypeOf(), which follows one object’s link:

Language: JavaScript
function Kit(code) {
  this.code = code;
}

const drilling = new Kit("KIT-17");
console.log(Object.getPrototypeOf(drilling) === Kit.prototype);
console.log(Object.getPrototypeOf(Kit) === Kit.prototype);

Before you run it, predict the output of both comparisons. Is Kit.prototype the kit’s prototype, the function’s, or both? Here’s what JavaScript prints:

Language: Program Output
true
false

Only the kit links to Kit.prototype, the prototype shared by the objects new Kit() creates. Kit itself is an ordinary function, so it links to Function.prototype, which is where shared function methods such as .call() live:

Language: JavaScript
function Kit(code) {
  this.code = code;
}

console.log(Object.getPrototypeOf(Kit) === Function.prototype);
console.log(Kit.call === Function.prototype.call);
console.log(Object.hasOwn(Kit, "call"));

.call() lives on Function.prototype, and Kit has no copy of its own:

Language: Program Output
true
true
false

Python has a similar split, because a class is an object too. type(drilling) is Kit, and type(Kit) is type, much as Kit links to Function.prototype. The match is loose. Function.prototype is itself a callable function object whose job here is holding .call() and friends, and a kit links to the separate Kit.prototype instead of to Kit.

Drawn out, drilling, Kit, and Kit.prototype form a triangle, and Kit’s own link leads out of it:

Language: Text
              .prototype (a property)
       Kit  ------------------------->  Kit.prototype
        | \                                 ^
        |  \  new Kit("KIT-17") makes       | links to
        |   \                               |
        |    `----------> drilling ---------'
        | links to
        v
  Function.prototype

The .prototype arrow is an ordinary property. The “links to” arrows are what Object.getPrototypeOf() follows, and the “makes” arrow only records what new did once. Kit keeps no reference to drilling. When you’re unsure, ask Object.getPrototypeOf() about the object in front of you instead of going by the property name.

Read a Class as a Constructor Function

The same three objects sit behind every class. Here’s the checkout app’s modern kit, written the way new JavaScript code should be:

Language: JavaScript
class ModernKit {
  constructor(code) {
    this.code = code;
  }

  describe() {
    return `${this.code}: tool kit`;
  }
}

const drilling = new ModernKit("KIT-17");
console.log(drilling.describe());
console.log(Object.getPrototypeOf(drilling) === ModernKit.prototype);
console.log(Object.keys(ModernKit.prototype));

The class gives its instances ModernKit.prototype, but listing the prototype’s keys finds nothing:

Language: Program Output
KIT-17: tool kit
true
[]

To read a class, translate it into the older form. The constructor body becomes the function body, and each method becomes a function stored on .prototype:

Language: JavaScript
function ModernKit(code) {
  this.code = code;
}

ModernKit.prototype.describe = function () {
  return `${this.code}: tool kit`;
};

const drilling = new ModernKit("KIT-17");
console.log(drilling.describe());
console.log(Object.getPrototypeOf(drilling) === ModernKit.prototype);
console.log(Object.keys(ModernKit.prototype));

The older form builds the same three objects, but this time the key shows up:

Language: Program Output
KIT-17: tool kit
true
[ 'describe' ]

The first two lines match, so the model holds for where things live. The third shows where the model falls short. Class methods are non-enumerable, so Object.keys() skips them, though Object.hasOwn(ModernKit.prototype, "describe") is still true. Class bodies always run in strict mode too, a set of tighter language rules that ECMAScript (ES) modules apply by default.

A class’s .prototype property is read-only, so assigning a new object to ModernKit.prototype throws a TypeError, though you can still add methods to the object it holds.

The bigger difference is construction. A class constructor runs only during object construction, normally through new or a subclass’s super(). JavaScript rejects plain calls to class constructors, with or without extends. Older code sometimes uses .call() to run a constructor on an existing object. The first argument to .call() becomes this, much like passing self when you call Kit.__init__(kit, code) by hand in Python:

Language: JavaScript
function Kit(code) {
  this.code = code;
}

const blank = {};
Kit.call(blank, "KIT-17");
console.log(blank.code);

The constructor function sets code on the object you passed:

Language: Program Output
KIT-17

You can’t use .call() this way with a class:

Language: JavaScript
class ModernKit {
  constructor(code) {
    this.code = code;
  }
}

ModernKit.call({}, "KIT-17");

Python lets you rerun Kit.__init__() on an existing kit, but a JavaScript class rejects the equivalent call. This shortened output omits the source context and stack trace:

Language: Program Output
...
TypeError: Class constructor ModernKit cannot be invoked without 'new'
...

Use class when you write new code. The constructor initializes per-kit state, and the prototype shares the methods. Keep the function form for reading older code, and remember that Kit.prototype is the prototype of the kits Kit makes, while Kit itself links to Function.prototype.

In the next exercise, Separate the Inspection Notes, you’ll repair the inspection note factory for two new kits, KIT-31 sanding and KIT-44 painting.

Become a Member to join the conversation.