JavaScript `with` alternative when creating DOM elements

Say I have a JavaScript library to create a DOM fragment, as shown below.

<main>
  <h1>A heading</h1>
  <p>A paragraph</p>
</main>

where the library domlibhas methods for any type of element, and the function generating the above fragment may look like this:

function(domlib){
  return domlib.main(
    domlib.h1('A heading'),
    domlib.p('A paragraph')
  );
}

Inside this function, I would like to call methods domlibas follows:

main(
  h1('A heading'),
  p('A paragraph')
)

To achieve this, I could place all the methods domlibin a global area, but I would prefer not to pollute the global area. For me, this is apparently the case when the statement withwould be the perfect solution:

function(domlib){
  with(domlib){
    return main(
      h1('A heading'),
      p('A paragraph')
    );
  }
}

Despite the fact that the operator iswith supported, it is practically not recommended and it will display an error in strict mode .

, , domlib , , ( domlib ) .

, , , , with?

+4
3

, , - , , .

, - :

const component = ({main, h1, p}) => main(
  h1('A heading'),
  p('A paragraph')
);

const component = (domlib) => {
  const {main, h1, p} = domlib;
  return main(
    h1('A heading'),
    p('A paragraph')
  );
};
+6

es6 :

const functionName = ({ main, h1, p }) => main(h1('heading'), p('paragraph'))

functionName(domlib)

, es6

+1

Another option is to redesign domlibto support the chain in the same way as

domlib
    .begin('main')
        .h1('A heading')
        .p('A paragraph')
    .end()

... but in real code it is better to replace domlibwith $or _:

function($){
    return $.main(
       $.h1('A heading'),
       $.p('A paragraph')
    );
}

The overhead of two extra characters for each call is a reasonable price to avoid tricks and hacks.

+1
source

Source: https://habr.com/ru/post/1693712/


All Articles