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;
It brings pain and suffering among you and others
It isn't a function (as was indicated in the question title before it was edited) but a statement. It may make more sense if the code sample is formatted like so:
Regarding what it does (Source)
Which means that in the code sample, it is first checked if
options
is a property ofsObj
. If it is thenoptions
refers tosObj.options
, otherwise it checks other scopes for a variable defined by the nameoptions
The downside of using a
with
statement is that it is impossible to know from just glancing at the code what gets accessed. There are other better alternatives as shown in this article