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条回答
干净又极端
2楼-- · 2020-02-21 22:34

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.

查看更多
放我归山
3楼-- · 2020-02-21 22:37

Your example could be rewritten as...

return sObj.options[selectedIndex].value;

...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..

with (sObj) 
{
   if(options[selectedIndex].value < 10){
       options[selectedIndex].value++;
       total+ = options[selectedIndex].value;
   }
}

But, having said that, it's often the case that saving typing can be achieved in better ways.

查看更多
Evening l夕情丶
4楼-- · 2020-02-21 22:38

the with statement is pure syntactical sugar, but it also can cause some nasty bugs.

See with Statement Considered Harmful for clarification:

If you can't read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.

查看更多
做个烂人
5楼-- · 2020-02-21 22:38

In that with block you dont have to type:

sObj.options[selectedIndex].value

but you can just use:

options[selectedIndex].value
查看更多
闹够了就滚
6楼-- · 2020-02-21 22:41

It adds to the scope of the statements contained in the block:

return sObj.options[selectedIndex].value;

can become:

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

In your case, it doens't do a whole lot...but consider the following:

var a, x, y;
var r = 10;
a = Math.PI * r * r;
x = r * Math.cos(PI);
y = r * Math.sin(PI /2);

Becomes:

var a, x, y;
var r = 10;
with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

...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

查看更多
7楼-- · 2020-02-21 22:50

Its the equivalent of

return sObj.options[selectedIndex].value;

With lets you issue a block of statements in the context of a particular object. Therefore all of the statements in the with 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

查看更多
登录 后发表回答