Possible Duplicate:
Are there legitimate uses for JavaScript’s “with” statement?
我最近发现在 JavaScript 中,可以执行如下操作:
with (document) {
write('foo');
body.scrollTop = x;
}
这样做的缺点是需要检查每个变量以确定它是否属于文档对象,从而产生很大的开销。
或者,可以这样做:
var d = document;
d.write('foo');
d.body.scrollTop = x;
是否存在可以合理使用“with”关键字的情况?
只是不要使用它:
http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/
JavaScript's with
statement was intended to provide a shorthand for writing recurring accesses to objects. So instead of writing
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
You can write
with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
bing = true;
bang = true;
}
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...
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...