Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/dash-wasm/src/util.ts
1067 views
1
// I wrote this in packages/util/misc in cocalc and copied it here. -- William Stein
2
3
// TODO: this is also in python-wasm/src/util.ts -- refactor somewhere...
4
5
// Get *all* methods of an object (including from base classes!).
6
// See https://flaviocopes.com/how-to-list-object-methods-javascript/
7
// This is used by bind_methods below to bind all methods
8
// of an instance of an object, all the way up the
9
// prototype chain, just to be 100% sure!
10
function get_methods(obj: object): string[] {
11
let properties = new Set<string>();
12
let current_obj = obj;
13
do {
14
Object.getOwnPropertyNames(current_obj).map((item) => properties.add(item));
15
} while ((current_obj = Object.getPrototypeOf(current_obj)));
16
return [...properties.keys()].filter(
17
(item) => typeof obj[item] === "function"
18
);
19
}
20
21
// Bind all or specified methods of the object. If method_names
22
// is not given, binds **all** methods.
23
// For example, in a base class constructor, you can do
24
// bind_methods(this);
25
// and every method will always be bound even for derived classes
26
// (assuming they call super if they overload the constructor!).
27
// Do this for classes that don't get created in a tight inner
28
// loop and for which you want 'safer' semantics.
29
export function bind_methods<T extends object>(
30
obj: T,
31
method_names: undefined | string[] = undefined
32
): T {
33
if (method_names === undefined) {
34
method_names = get_methods(obj);
35
method_names.splice(method_names.indexOf("constructor"), 1);
36
}
37
for (const method_name of method_names) {
38
obj[method_name] = obj[method_name].bind(obj);
39
}
40
return obj;
41
}
42
43