问题描述
我最近发现,在JavaScript中,人们可以执行以下操作:
I recently discovered that in JavaScript, one can do something like the following:
with (document) {
write('foo');
body.scrollTop = x;
}
缺点是需要检查每个变量是否属于文档对象,这会产生很大的开销.
The down side of this is that each variable needs to be checked to see if it belongs to the document object, creating a significant overhead.
或者,人们可以做这样的事情:
Alternatively, one could do something like this:
var d = document;
d.write('foo');
d.body.scrollTop = x;
在任何情况下都可以合理地使用'with'关键字吗?
Are there any situations where the use of the 'with' keyword is justified?
推荐答案
请不要使用它: http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
你可以写
with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
bing = true;
bang = true;
}
看起来好多了.除了一件事.通过查看代码,您无法分辨出哪些 bing
和 bang
会被修改.会修改 ooo.eee.oo.ah_ah.ting.tang.walla.walla
吗?还是全局变量 bing
和 bang
被破坏?不可能肯定知道...
That looks a lot nicer. Except for one thing. There is no way that you can tell by looking at the code which bing
and bang
will get modifed. Will ooo.eee.oo.ah_ah.ting.tang.walla.walla
be modified? Or will the global variables bing
and bang
get clobbered? It is impossible to know for sure...
如果您无法阅读程序并确信自己知道该程序将要执行的操作,则不能确定该程序可以正常工作.因此,应避免使用 with
语句...
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...
这篇关于为什么要使用"with"JavaScript中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!