YoniGeek
YoniGeek

Reputation: 4093

How does this JavaScript-pattern works: Namespaced constructor

I'm having problems to understand how this operation:

tmp.setAttribute(i, prop[i]);

goes through in this for-loop. How prop-array creates 2 arguments. As I understand var = i is just a variable right? But apparently it becomes the 1:st argument in the method just like that?

Thanks for your time.

http://jsbin.com/ozoqob/2/edit

var MYAPP = MYAPP || {}; 

MYAPP.dom = {};
   MYAPP.dom.Element = function(type, prop){
     var tmp = document.createElement(type);
     for (var i in prop) {
       tmp.setAttribute(i, prop[i]);
       /*
       WHAT I DONT UNDERSTAND IS HOW THIS FOR-LOOP DIVIDE THE ARRAY IN TWO ARGUMENTS?? BEACAUSE 'I' IS JUST A VARIABLE WHICH IS USED TO LOOP THRU THE ARRAY BUT APPARENTLY NOT RIGHT?
       */
       console.log(i); // how? is this arguments divided?
       console.log(prop[i]);
     }
  return tmp; 
   };

var el1 = new MYAPP.dom.Element(
       'a',
       {href:'http://phpied.com'}
   );

console.log(el1);

Upvotes: 0

Views: 77

Answers (2)

Shuping
Shuping

Reputation: 5468

2 concepts:

  1. every object in JavaScript is a hash table thus you can access its property value by a key e.g. obj[key];
  2. the for-in loop in JavaScript loops keys in the target object (instead of looping values)

In your code, for (var i in prop) loops all the keys in object prop and stores each key in i. So, for each key i, you can get its value by prop[i].

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

You pass an object as the 2nd argument to the method. You then enumerate the properties of that object with a for...in loop. At every iteration of the loop, i will refer to the identifier of a property of the object, and prop[i] will therefore refer to the value of that property:

var prop = {
    prop1: "value1",
    prop2: "value2"
};

for (var i in prop) {
    console.log(i); // "prop1", "prop2"
    console.log(prop[i]); // "value1", "value2"
}

This behaviour is explained in the spec, and is summed up by this line if you imagine P is i in the above example:

Let P be the name of the next property of obj whose [[Enumerable]] attribute is true.

Upvotes: 0

Related Questions