I saw JavaScript code which begins with with
. That's a bit confusing. What does it do and how can it be used correctly?
with (sObj) return options[selectedIndex].value;
I saw JavaScript code which begins with with
. That's a bit confusing. What does it do and how can it be used correctly?
with (sObj) return options[selectedIndex].value;
I would recommend NOT using this because of performance issues, but what the above means is:
for the object sObj (here presumably a select element), all children and properties referenced on this one (or between following curly braces) treat that as their parent scope.
Your example could be rewritten as...
...as the 'with' statement places all related statements in the scope of the supplied object. In this case, it's pretty pointless but, if you were doing lots of operations on 'sObj', then it saves a lot of typing.
Totally ficticious example..
But, having said that, it's often the case that saving typing can be achieved in better ways.
the
with
statement is pure syntactical sugar, but it also can cause some nasty bugs.See with Statement Considered Harmful for clarification:
In that with block you dont have to type:
but you can just use:
It adds to the scope of the statements contained in the block:
can become:
In your case, it doens't do a whole lot...but consider the following:
Becomes:
...saves a couple of keystrokes. The Mozilla documentation actually does a pretty good job of explaining things in a little more detail (along with pros and cons of using it):
with - Mozilla Developer Center
Its the equivalent of
With
lets you issue a block of statements in the context of a particular object. Therefore all of the statements in thewith
block are taken to be members of the object in parenthesis.This can make code more readable at times, but it also can lead to ambiguity, since the variable references can either be with sObj or global.
legitimate uses for javascript's "with" statement :D