javascript - 为什么在 JavaScript 中使用 "with"关键字?

标签 javascript

<分区>

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

关于javascript - 为什么在 JavaScript 中使用 "with"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1931186/

相关文章:

javascript - 如何检测我的计算机规范并在浏览器中显示?

javascript - 使用 Quasar-Framework 0.15 进行 Jest 单元测试配置

javascript - 访问传递给原型(prototype)函数的值

javascript - 从实例化函数中获取函数名

javascript - Angular 绑定(bind)字符串到单独的行到 html

javascript - 当正则表达式匹配空字符串时,是否可以用 regexp.exec 循环模拟 string.match?

javascript - 为什么 _.some 在没有迭代器函数的情况下运行?

javascript - 如何对具有不同键的对象数组进行排序

javascript - Protractor :失败:row.findElement 不是函数

javascript - 将特定图像从一个 div 克隆到另一个 div 但更改 onClick 和 ID