Scope Injection or Workaround in JavaScript

73 Views Asked by At

I am working on a library and I have this code. I have the following pattern. Let's say there's a function executeWithinScope:

// example 1
function executeWithinScope(callback) {
  // Globally defined variable
  Tracker.currentScope = new Scope(); // {}
  callback();
  Tracker.currentScope = null;
}

Note, that Scope functionality does not matter it might also be an empty object for this example.

Then, I have a function modifyScope that is intended to be used from inside the callback and it modifies the Tracker.currentScope.

// example 2
function modifyScope() {
  Tracker.currentScope.beModified(); // or do something else to the current scope
}

The global variable approach works nicely when callback is not async, but

// example 3
executeWithinScope(async () => {
  modifyScope(); // scope will remain when modifyScope is called
  modifyScope(await somethingAsync()); // scope will be null modifyScope is called
});

I tried experimenting with eval api, but JS functions are lexically scoped, so I could not inject something inside the callback function.

So my question is: is there a way to do a scope injection or a different approach, so that all modifyScope functions that are called within callback are called with the same variable in its context preserving current syntax?

IDEALLY, the code in the example 3 must not be changed at all, only in the executeWithinScope and modifyScope functions.

Also, I could pass scope into the callback and pass it to modifyScope every time I call it, but it makes it annoying to do every time and makes seem redundant.

// example 4
executeWithinScope(async (scope) => {
  modifyScope(scope); // scope will remain when modifyScope is called
  modifyScope(scope, await somethingAsync()); // scope will be null modifyScope is called
});

or even

// example 5
executeWithinScope(async (scope) => {
  modifyScope.call(scope); // scope will remain when modifyScope is called
  modifyScope.call(scope, await somethingAsync()); // scope will be null modifyScope is called
});

Please, let me know of any other strategy. The code really should stay as it is in the example 3

0

There are 0 best solutions below