开发者

Why do object literals in javascript save unnecessary DOM references?

开发者 https://www.devze.com 2023-03-26 09:42 出处:网络
From this document, Don\'t do this car = new Object(); car.make = \"Honda\"; car.model = \"Civic\"; car.transmission = \"manual\";

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?


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号