-
-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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.
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 descriptorAll functions are exported by their names. There is no default export.
API
Reference