为什么要使用"with"JavaScript中的关键字? [英] Why use "with" keyword in JavaScript?

查看:50
本文介绍了为什么要使用"with"JavaScript中的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
JavaScript的"with"语句是否合法使用?

我最近发现,在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/

JavaScript的 with 语句旨在为编写对对象的定期访问提供一种捷径.所以不用写

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;

你可以写

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中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆