I came across something strange, and I wanted to share it with you so that you could help to my frustration. (it took me a while to figure out what was wrong)
I wanted to create a recursive function that would render a tree like data structure on a nested <ul>
element.
The data structure was in this form:
var contents = [
{
name : 'test',
contents : [
{
name : 'test > test 1'
},
{
name : 'test > test 2'
},
{
name : 'test > test 3'
}
]
},
{
name : 'test 2'
}
];
I added my code on a object block as such:
var dummy = {
do : function() {
var element = $('<ul>');
dummy.recursive(element, contents);
$("#content").append(element);
},
recursive : function( element, contents ) {
for( i = 0; i < contents.length; i++ ) {
var item = contents[i];
var li = $('<li> (' + i + ') ' + item.name + '</li>');
if( item.contents && item.contents.length ) {
var ul = $('<ul>');
dummy.recursive(ul, item.contents);
li.append(ul);
}
element.append(li);
}
}
};
I found out that the variable i
after dummy.recursive
had run on the contents of the first element was no longer 0 but instead 2. This means that although i
is in its private context is being replaced by the recursive function.
I've also added a jsfiddle to illustrate the problem here: http://jsfiddle.net/MWQJC/2/
The problem is in the variable i
not being explicitly declared by doing a var i = 0
on the beginning of the function. (As illustrated here: http://jsfiddle.net/h8gtd/1/)
It looks like by default every undeclared variable accessed is being created in the object scope. Is this so?