在 javascript 中使用 with 是不好的做法吗?
我认为像 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑到它如何影响作用域链,我将其称为不好的做法。
看看 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"
马特的回答中的链接的简短摘要是,使用“with”语句的问题是“with”块中的变量不明确。使用以下示例:
如果您不确定 foo.doo.diddly.doo 是否具有 bar 或 baz 属性,则您不知道 with 语句中的 bar 和 baz 是否正在执行,或者某些全局 bar 和巴兹。最好使用变量:
不过,在您的示例中,数学几乎不是一个足够长的术语来证明即使使用变量也是合理的,但我猜您想到的应用程序比您在问题中使用的应用程序更详细。
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:
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:
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.
如果您访问(嵌套)对象属性一次,则无需“缓存”它们。
但是,如果您多次访问它们,那么您应该将引用存储在局部变量中。这有两个优点:(
现在与
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:
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.