Is javascript used in bad practice?

I think things like with(Math){document.body.innerHTML= PI} would not be good practice.

+4
source share
3 answers

I would call it bad practice, given how this affects the scope chain.

Take a look at this article from Douglas Crockford: โ€œ with an expression considered malicious โ€

+5
source

A brief overview of the links in Matt's answer is that the problem with using the c operator is that the variables in the c block are ambiguous. Using the following example:

 with(foo.doo.diddly.doo){ bar = 1; baz = 1; } 

If you are not completely sure that foo.doo.diddly.doo has bar or baz properties, you donโ€™t know if bars and baz are executed in the WITH statement, or some kind of global bar and base. Better to use variables:

 var obj = foo.doo.diddly.doo; obj.bar = 1; obj.baz = 1; 

In your example, however, the math is hardly long enough to justify even using a variable, but I assume that you have a more detailed application than you used for the question.

+4
source

If you request one (nested) object properties once, then there is no need to "cache" them.

But if you access them more than once, you should save the link in a local variable. This has two advantages:

  • (nested) properties do not need to be searched more than once (potentially in the inheritance chain, which is slow!).
  • Especially global objects (but any object that is not in the current area), you only need to look in the chain of visibility areas. Subsequent access will be faster.

And now the connection to with :

It generates a new area at the beginning of the current area chain. This means that any access to other variables / objects will cost at least one region scan more, even for variables that are local to the function.

0
source

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


All Articles