什么是“与...”用JavaScript做什么? [英] What does "with" do in JavaScript?
本文介绍了什么是“与...”用JavaScript做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到的JavaScript代码以开头,带
。这有点令人困惑。它做了什么以及如何正确使用?
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;
推荐答案
它增加了包含在block:
It adds to the scope of the statements contained in the block:
return sObj.options[selectedIndex].value;
可以成为:
with (sObj)
return options[selectedIndex].value;
在你的情况下,它并没有做很多......但请考虑以下因素: / p>
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);
成为:
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
...保存几次按键。 Mozilla文档实际上可以更详细地解释一些事情(以及使用它的优点和缺点):
...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
这篇关于什么是“与...”用JavaScript做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文