What does “with” do in JavaScript?

2020-02-21 22:24发布

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;

8条回答
干净又极端
3楼-- · 2020-02-21 22:54

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:

with (sObj){
    return options[selectedIndex].value;
}

Regarding what it does (Source)

The with statement establishes the default object for a set of statements. JavaScript looks up any unqualified names within the set of statements to determine if the names are properties of the default object. If an unqualified name matches a property, then the property is used in the statement; otherwise, a local or global variable is used.

Which means that in the code sample, it is first checked if options is a property of sObj. If it is then options refers to sObj.options, otherwise it checks other scopes for a variable defined by the name options

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

查看更多
登录 后发表回答