Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do object literals in javascript save unnecessary DOM references?

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?

like image 394
Amir Raminfar Avatar asked Aug 05 '11 17:08

Amir Raminfar


2 Answers

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

like image 121
KARASZI István Avatar answered Nov 01 '22 11:11

KARASZI István


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);
like image 40
rav Avatar answered Nov 01 '22 13:11

rav