Say, I have a JavaScript library to produce a DOM fragment like the following
<main>
<h1>A heading</h1>
<p>A paragraph</p>
</main>
where the library, domlib
, has methods for any type of element, and a function generating the fragment above could look like this:
function(domlib){
return domlib.main(
domlib.h1('A heading'),
domlib.p('A paragraph')
);
}
Within this function I would rather like to call the domlib
methods like this:
main(
h1('A heading'),
p('A paragraph')
)
To achieve this, I could place all the methods of domlib
in the global scope, but I would rather avoid to pollute the global scope. To me, this appears to be a case where the with
statement would have been an ideal solution:
function(domlib){
with(domlib){
return main(
h1('A heading'),
p('A paragraph')
);
}
}
Although still supported, the with
statement is practically deprecated, and will throw an error in strict mode.
I do not see many other options, except to assign domlib
methods to local function variables, but that would easily result in assigment of dozens of local variables, in which case the first approach (calling methods on domlib
directly) would lead to simpler code.
My question is, is there any other alternative to achieve what I want, with similar simplicity and readability as using a with
statement?
If you are looking for an alternative for back-end development the most viable options could be Python, Ruby, Kotlin or PHP, for instance. If your purpose is front-end development, TypeScript, CoffeeScript, Elm, ClojureScript or Dart could be the better alternatives.
The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property.
The method I would use is to explicitly list the elements I want via destructuring.
For example, in your case I would have something like this:
const component = ({main, h1, p}) => main(
h1('A heading'),
p('A paragraph')
);
This is similar to doing
const component = (domlib) => {
const {main, h1, p} = domlib;
return main(
h1('A heading'),
p('A paragraph')
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With