为什么 JavaScript 中的对象字面量会保存不必要的 DOM 引用?

发布于 2024-11-28 06:57:32 字数 687 浏览 1 评论 0原文

文档中,

不要这样做,

car = new Object();
car.make = "Honda";
car.model = "Civic";
car.transmission = "manual";
car.miles = 1000000;
car.condition = "needs work";

而是这样做,

car = {
  make: "Honda",
  model: "Civic",
  transmission: "manual",
  miles: 1000000,
  condition: "needs work"
}

因为

这可以节省空间和不必要的 DOM 引用。

但是 DOM 只是操作 HTML、XHTML 或 XML 中的对象。以上与 DOM 无关。

这是错误的吗?或者我错过了什么?有人可以帮助我理解本文讨论的 DOM 参考吗?

From this document,

Don't do this

car = new Object();
car.make = "Honda";
car.model = "Civic";
car.transmission = "manual";
car.miles = 1000000;
car.condition = "needs work";

Do this instead

car = {
  make: "Honda",
  model: "Civic",
  transmission: "manual",
  miles: 1000000,
  condition: "needs work"
}

Because

This saves space and unnecessary DOM references.

But DOM is just manipulating object in HTML, XHTML or XML. The above has nothing to do with the DOM.

Is this wrong? Or am I missing something? Can someone help me understand what DOM reference this article is talking about?

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

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

发布评论

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

评论(2

此刻的回忆 2024-12-05 06:57:32

我认为作者想写对象引用。 DOM 引用没有任何意义。

I think the author wanted to write Object references. DOM references makes no sense.

捂风挽笑 2024-12-05 06:57:32

这里实际上有两点需要解决:

1)它将语句执行的数量从 6 个减少到 1 个。我不确定这在实践中是否更快,但理论上应该如此。至少,它确实使代码更清晰、更易读。

2) 如果在浏览器中执行此代码,则汽车对象会添加到 DOM,因为它会添加到窗口对象。

此代码将发出“LOL”警报:

var foo = "LOL";
alert(window.foo);

There's actually two points to address here:

1) It lessens the number of statement executions from 6 to 1. I am not sure if this is faster in practical terms, but in theory it should be. At the very least, it does make for cleaner, more readable code.

2) If this code is executed in the browser, the car object DOES get added to the DOM, because it gets added to the window object.

This code will alert "LOL":

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