Skip to content

Prototypes

Eugene Lazutkin edited this page Aug 15, 2024 · 5 revisions

JavaScript uses a prototypal inheritance model to support OOP. Surprisingly, the set of tools to work with prototypes is relatively small:

This module contains a set of utilities to work with prototypes.

prototypes.js

The following utilities are available:

Function Return value Description
prototypes(object, skipSelf) generator Iterate over prototypes.
getPropertyDescriptor(object, name) descriptor Get property descriptor from all prototypes.

prototypes() is a generator that yields all prototypes of an object. It starts with the object itself, and stops when it reaches the default prototype or null. The object is skipped if skipSelf is truthy.

getPropertyDescriptor() is similar to Object.getOwnPropertyDescriptor(), but returns the descriptor of the effective property in all prototypes.

Examples

import {prototypes, getPropertyDescriptor} from 'meta-toolkit/prototypes.js';

class Foo {
  foo() { return 'foo'; }
}

class Bar extends Foo {
  bar() { return 'bar'; }
}

const x = new Bar();

for (const proto of prototypes(x)) {
  // x
  // Bar
  // Foo
  console.log(proto.constructor?.name); // Bar, Bar, Foo
}

Object.getOwnPropertyDescriptor(x, 'foo'); // undefined
getPropertyDescriptor(x, 'foo'); // real descriptor

Object.getOwnPropertyDescriptor(x, 'bar'); // undefined
getPropertyDescriptor(x, 'bar'); // real descriptor

Exports

All functions are exported by their names. There is no default export.

Clone this wiki locally