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).
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!
– Vinícius Lara
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. :/
– Luiz Felipe