From a5dfaf8c5eb2d344a5e8320d5c394686f4a2e584 Mon Sep 17 00:00:00 2001 From: benStre Date: Thu, 18 Jan 2024 15:59:24 +0100 Subject: [PATCH] add distinction between arrow and normal functions for 'this' injection --- types/function-utils.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/types/function-utils.ts b/types/function-utils.ts index ab888f49..6b717aeb 100644 --- a/types/function-utils.ts +++ b/types/function-utils.ts @@ -182,6 +182,7 @@ export function createFunctionWithDependencyInjections(source: string, dependenc const hasThis = Object.keys(dependencies).includes('this'); const renamedVars = Object.keys(dependencies).filter(d => d!=='this').map(k=>'_'+k); const varMapping = renamedVars.map(k=>`const ${k.slice(1)} = ${allowValueMutations ? 'createStaticObject' : ''}(${k});`).join("\n"); + const isArrow = isArrowFunction(source); const createStaticFn = `function createStaticObject(val) { if (val && typeof val == "object" && !globalThis.Datex?.Ref.isRef(val)) { @@ -193,8 +194,12 @@ export function createFunctionWithDependencyInjections(source: string, dependenc try { let creatorFn = new Function(...renamedVars, `"use strict";${(varMapping&&allowValueMutations)?createStaticFn:''}${varMapping}; return (${source})`) - if (hasThis) creatorFn = creatorFn.bind(dependencies['this']) - return creatorFn(...Object.entries(dependencies).filter(([d]) => d!=='this').map(([_,v]) => v)); + // arrow function without own this context - bind creatorFn to this + if (hasThis && isArrow) creatorFn = creatorFn.bind(dependencies['this']) + const fn = creatorFn(...Object.entries(dependencies).filter(([d]) => d!=='this').map(([_,v]) => v)); + // normal function - bind directly to this + if (hasThis && !isArrow) return fn.bind(dependencies['this']) + else return fn; } catch (e) { console.error(source)