0

I am working on a large library and I want to reduce conflicts in the code as much as possible. I have a function like this:

((privateArgument) => {

     var transformed = privateArgument.someProperty;
     userCallback(); // This should only have access to transformed

})({someProperty: 'Hello, world!'});

I should mention that I tried to simplify the example as much as possible to illustrate my intention. In reality, I have no control over the value passed to the function ({someProperty: 'Hello, world!'}).

And an example of the userCallback:

() => {

     console.log(transformed); // Can be used here freely
     console.log(privateArgument); // Can unfortunately also be accessed

}

I have tried the following:

  • Setting privateArgument = undefined: breaks access to transformed and does not throw the native "undefined" error
  • Overriding the privateArgument by defining a new let privateArgument and scoping the userCallback with {}: gives me an error, saying that I cannot redefine it
  • Passing transformed as an argument to userCallback: does nothing to address the issue

Please note that I am specifically asking about arguments, not regular variables such as var and let. I am aware that the issue regarding normal variables has already been addressed in other questions. However, the answers to those questions are not helpful for this particular issue.

If anyone knows of a scoping mechanism I can utilize for this or how to completely get rid of the privateArgument (so that it throws the native error and can be re-declared in the userCallback) it would be greatly appreciated.

Ood
  • 1,445
  • 4
  • 23
  • 43
  • 2
    What you ask for is basically impossible. Scope is static in JS, what you are expecting is dynamic scope. Arguments still work the same as variables. – VLAZ Feb 12 '23 at 18:21
  • @VLAZ I thought that this might be the case. However, I was hoping that someone might know of a trick to implement this, that I am not aware of. – Ood Feb 12 '23 at 18:23

0 Answers0