Question

I'm thinking that stuff like with(Math){document.body.innerHTML= PI} wouldn't exactly be good practise.

Was it helpful?

Solution

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

Take a look at this article from Douglas Crockford: "with Statement Considered Harmful"

OTHER TIPS

The short summary of the link in Matt's answer is that the problem with using the "with" statement is that the variables within the "with"'s block are ambiguous. Using the following example:

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

If you're not absolutely certain that foo.doo.diddly.doo has the bar or baz properties, you don't know if the bar and baz within the with statement are getting executed, or some global bar and baz. It's better to use variables:

var obj = foo.doo.diddly.doo;

obj.bar = 1;
obj.baz = 1;

In your example, though, Math is hardly a long enough term to justify even using a variable, but I'm guessing you have a more verbose application in mind than you've used for the question.

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

But if you access them more then once, then you should store a reference in a local variable. This has two advantages:

  1. (nested) properties don't need to be lookup up more then once (potentially in the inheritance chain which is slow!).
  2. Especially global objects (but any object that is not in the current scope) only needs to be looked up once in the scope chain. Subsequent access will be faster.

And now the connection to with:

It generates a new scope at beginning of the current scope chain. That means that any access to other variables/objects will cost at least one scope lookup more, even to variables that are local to the function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top