// I wrote this in packages/util/misc in cocalc and copied it here. -- William Stein12// Get *all* methods of an object (including from base classes!).3// See https://flaviocopes.com/how-to-list-object-methods-javascript/4// This is used by bind_methods below to bind all methods5// of an instance of an object, all the way up the6// prototype chain, just to be 100% sure!7function get_methods(obj: object): string[] {8let properties = new Set<string>();9let current_obj = obj;10do {11Object.getOwnPropertyNames(current_obj).map((item) => properties.add(item));12} while ((current_obj = Object.getPrototypeOf(current_obj)));13return [...properties.keys()].filter(14(item) => typeof obj[item] === "function"15);16}1718// Bind all or specified methods of the object. If method_names19// is not given, binds **all** methods.20// For example, in a base class constructor, you can do21// bind_methods(this);22// and every method will always be bound even for derived classes23// (assuming they call super if they overload the constructor!).24// Do this for classes that don't get created in a tight inner25// loop and for which you want 'safer' semantics.26export function bind_methods<T extends object>(27obj: T,28method_names: undefined | string[] = undefined29): T {30if (method_names === undefined) {31method_names = get_methods(obj);32method_names.splice(method_names.indexOf("constructor"), 1);33}34for (const method_name of method_names) {35obj[method_name] = obj[method_name].bind(obj);36}37return obj;38}394041