在 javascript 中使用 with 是不好的做法吗?

发布于 2024-10-09 15:27:26 字数 82 浏览 6 评论 0原文

我认为像 with(Math){document.body.innerHTML= PI} 这样的东西并不完全是一个好的做法。

I'm thinking that stuff like with(Math){document.body.innerHTML= PI} wouldn't exactly be good practise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

战皆罪 2024-10-16 15:27:26

考虑到它如何影响作用域链,我将其称为不好的做法。

看看 Douglas Crockford 的这篇文章:“with被视为有害的声明

I would call it bad practice, considering how it affects the scope chain.

Take a look at this article from Douglas Crockford: "with Statement Considered Harmful"

遮云壑 2024-10-16 15:27:26

马特的回答中的链接的简短摘要是,使用“with”语句的问题是“with”块中的变量不明确。使用以下示例:

with(foo.doo.diddly.doo){
  bar = 1;
  baz = 1;
}

如果您不确定 foo.doo.diddly.doo 是否具有 bar 或 baz 属性,则您不知道 with 语句中的 bar 和 baz 是否正在执行,或者某些全局 bar 和巴兹。最好使用变量:

var obj = foo.doo.diddly.doo;

obj.bar = 1;
obj.baz = 1;

不过,在您的示例中,数学几乎不是一个足够长的术语来证明即使使用变量也是合理的,但我猜您想到的应用程序比您在问题中使用的应用程序更详细。

The short summary of the link in Matt's answer is that the problem with using the "with" statement is that the variables within the "with"'s block are ambiguous. Using the following example:

with(foo.doo.diddly.doo){
  bar = 1;
  baz = 1;
}

If you're not absolutely certain that foo.doo.diddly.doo has the bar or baz properties, you don't know if the bar and baz within the with statement are getting executed, or some global bar and baz. It's better to use variables:

var obj = foo.doo.diddly.doo;

obj.bar = 1;
obj.baz = 1;

In your example, though, Math is hardly a long enough term to justify even using a variable, but I'm guessing you have a more verbose application in mind than you've used for the question.

白况 2024-10-16 15:27:26

如果您访问(嵌套)对象属性一次,则无需“缓存”它们。

但是,如果您多次访问它们,那么您应该将引用存储在局部变量中。这有两个优点:(

  1. 嵌套)属性不需要多次查找(可能在继承链中查找,这很慢!)。
  2. 特别是全局对象(但任何不在当前作用域中的对象)只需要在作用域链中查找一次。后续访问会更快。

现在与 with 的连接:

它在当前作用域链的开头生成一个新作用域。这意味着对其他变量/对象的任何访问都将至少增加一次范围查找的成本,即使对于函数本地的变量也是如此。

If you access (nested) object properties once, then there is no need "cache" them.

But if you access them more then once, then you should store a reference in a local variable. This has two advantages:

  1. (nested) properties don't need to be lookup up more then once (potentially in the inheritance chain which is slow!).
  2. Especially global objects (but any object that is not in the current scope) only needs to be looked up once in the scope chain. Subsequent access will be faster.

And now the connection to with:

It generates a new scope at beginning of the current scope chain. That means that any access to other variables/objects will cost at least one scope lookup more, even to variables that are local to the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文