Skip to content

Commit

Permalink
Merge pull request #42 from unyt-org/fix-js-function-this
Browse files Browse the repository at this point in the history
Fix `this` injection for transferable arrow functions
  • Loading branch information
jonasstrehle authored Jan 21, 2024
2 parents a8b8949 + a5dfaf8 commit 0d2c2dd
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions types/function-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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)
Expand Down

0 comments on commit 0d2c2dd

Please sign in to comment.