javascript - 用with()可以吗?

标签 javascript

有一次,我看到这样一个例子:

var a, x, y;
var r = 10;
with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

它看起来很方便,因为这样我就不必输入所有的 Math.s.

但是当我看一下 MDN ,它说:

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

那么可以使用 with() 吗?在 HTML5 中?

最佳答案

您链接的 MDN 说 Using with is not recommended...
with 是制作午餐意大利面条代码的绝佳方式。

你可能喜欢它,但需要调试它的人会诅咒你。

javascript 有一些非常奇怪的运算符,比如逗号运算符(,)。
你能看懂以下代码的作用吗?

var a = "a";
var b = "b";
a = [b][b = a,0];

好吧,它交换了 a 和 b...您不了解 ,,因此需要维护您的 代码的人。不要使用 hack,hack 在字谜游戏中很酷,而不是在真实代码中。


When is the comma operator useful?
The comma swap Fiddle

关于javascript - 用with()可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864026/

相关文章:

javascript - 在 React JS 中设置 onClick 值

javascript - React - 将 `this` 绑定(bind)到导入的函数

javascript - 单次按下时触发不需要的多个 KeyDown 事件

javascript - Ember 数据、关系和 JSON

javascript - 如何检索选择框中所选选项的从零开始的索引?

javascript - 如何在 Django 中组织 JS 文件?

javascript - AngularJS 创建全局键盘快捷键的方法是什么?

javascript - 我的功能不断刷新

javascript - 如何转换对象数组?

javascript - 依赖查询参数来触发事件是否存在 JavaScript 中的安全风险