aboutsummaryrefslogtreecommitdiff
path: root/src/internal
diff options
context:
space:
mode:
authorShinigami <[email protected]>2023-07-18 07:23:26 +0200
committerGitHub <[email protected]>2023-07-18 05:23:26 +0000
commit5f947cbd4773f768a90243e54fd707c9769e8530 (patch)
tree6fa92071b458fc6a56e7e2f09ed99c07e504ffb8 /src/internal
parenta3a1480cb3ad9301b4e5e53ba8a281d1e170bca5 (diff)
downloadfaker-5f947cbd4773f768a90243e54fd707c9769e8530.tar.xz
faker-5f947cbd4773f768a90243e54fd707c9769e8530.zip
chore: enable strictBindCallApply (#2254)
Diffstat (limited to 'src/internal')
-rw-r--r--src/internal/bind-this-to-member-functions.ts24
1 files changed, 24 insertions, 0 deletions
diff --git a/src/internal/bind-this-to-member-functions.ts b/src/internal/bind-this-to-member-functions.ts
new file mode 100644
index 00000000..db0d3885
--- /dev/null
+++ b/src/internal/bind-this-to-member-functions.ts
@@ -0,0 +1,24 @@
+/**
+ * Bind all functions of the given instance to itself so you can use them independently.
+ *
+ * @internal
+ *
+ * @param instance The class instance of which the methods are to be bound to itself.
+ *
+ * @example
+ * const someModule = new SomeModule(faker);
+ * bindThisToMemberFunctions(someModule); // Usually called inside the constructor passing `this`
+ * const someMethod = someModule.someMethod;
+ * someMethod(); // Works
+ */
+export function bindThisToMemberFunctions<TClass extends { new (): any }>(
+ instance: InstanceType<TClass>
+): void {
+ for (const name of Object.getOwnPropertyNames(
+ Object.getPrototypeOf(instance)
+ )) {
+ if (typeof instance[name] === 'function' && name !== 'constructor') {
+ instance[name] = instance[name].bind(instance);
+ }
+ }
+}