How to expose a set of functions that is within an object in the global scope?

Asked

Viewed 49 times

3

I’m building a Javascript API that returns a set of functions accessible through an object.

Every time I want to access some of these functions, I need to enunciate the object, for example: minhaAPI.funcao1, yet I didn’t want to have to do it every time.

I know I can do this:

const { funcao1 } = minhaAPI

so you can do:

funcao1()

instead of:

minhaAPI.funcao1()

However I am looking for a more automated method, where it is not necessary to enunciate all the functions that I will use.

What would be the best solution for this?

1 answer

5


I really wouldn’t advise it. First because you can pollute the global scope or even overwrite an original property in case of name conflict.

However, if you really have a good reason (which I find difficult), an option to do so would be to explicitly add all properties of the given object in the global scope, using something like globalThis (which is the same as window in browsers or global in Node.js):

const obj = {
  name: 'Foo',
  age: 123
};

Object.keys(obj).forEach((key) => {
  // ⛔️ NÃO RECOMENDO FAZER ISSO. É UM ANTI-PATTERN
  globalThis[key] = obj[key];
});

console.log(name); // 'Foo';
console.log(age); // 123

But note that this overwrite (literally) the global scope, which it’s not a good idea.

I could also use the statement with, but it is obsolete (precisely because extending the lexical scope from an object is not a desirable thing).

I would rethink the need for this, since it is undoubtedly a gambiarra. In this type of situation, being explicit is much better than implicit. Do not do things by "laziness" of writing a little more code, since declaring variables explicitly will, most of the time, always be better. Besides, if you have using Typescript, the explicit statement brings you type security without the need for additional settings.

In short, rethink the need for this. It is not as necessary as you think (and if it is, it is necessary to edit the answer, because "more automated" does not seem to me a good reason to search to overwrite the scope).

  • 1

    In Swift when you import a module the functions are arranged in the scope so that it is not necessary to enunciate the module every time. In my view this is a more interesting approach. Thank you for the answer!

  • 2

    I agree with you that is interesting and sometimes can end up helping, but unfortunately we do not have it in the JS, there has to be made explicitly even. :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.