gpt4 book ai didi

javascript - 用with()可以吗?

转载 作者:搜寻专家 更新时间:2023-11-01 05:06:49 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com