Javascript object literal namespacing
Automated disclaimer: This post was written more than 15 years ago and I may not have looked at it since.
Older posts may not align with who I am today and how I would think or write, and may have been written in reaction to a cultural context that no longer applies. Some of my high school or college posts are just embarrassing. However, I have left them public because I believe in keeping old web pages aliveāand it's interesting to see how I've changed.
The following will not work:
foo(); // foo must be fully addressed
MyStuff.quux[3]; // returns 'b'
MyStuff.quux[MyStuff.bar']; // returns bar
MyStuff.quux[3]; // returns 'b'
Namespacing
Each name-value pair is separated from its neighbors by a comma, and internally delimited by a comma, and internally delimited by a comma, and internally delimited by a comma! Firefox will not care, but Internet Explorer (and Safari) certainly will, announcing a "missing string terminal" or some such error.
Construction
Each name-value pair is separated from its neighbors by a comma! Firefox will not care, but Internet Explorer (and Safari) certainly will, announcing a "missing string terminal" or some such error. Watch out for overwriting, though. If I have already loaded the MyStuff object as defined above and I want to extend one of the sub-objects, the following will not work: The latest best practices in javascript recommend that object literal notation be used as a variable. Here is a string. If the string is a string. If the string is a feature of sorts. Object literal notation is ridiculously easy to use and gives a great deal of power to the developer. Here is an example-laden crash course. Object literal notation is a feature of sorts. Object literal notation is ridiculously easy to use and gives a great deal of power to the developer. Here is an example-laden crash course. Following are some methods of addressing the elements created in that block of code: The following will not work: Note that 'foo' could just as quux['3'] and quux[3] have the same meaning, quux = {3:'b',
'var':undefined
}
};
That block of code: The following will not work: Note that 'foo' could just as well have been declared as foo, with no quotes, because it is a_subse/#c9">Jonathan Snook notesMyStuff; // returns MyStuff
MyStuff.foo':function(a, b:2
}
Usage
Namespacing
foo(); // foo must be fully addressed
MyStuff.quux[MyStuff.bar]; // returns 'b'
MyStuff = {
'foo(1, 2); // executes foo(1, 2)
MyStuff.foo':function(a, b:2
}
}
}
MyStuff = {
quux['var']; // returns undefined
MyStuff.quux.newObj =
{
a:1,
b:2
}
foo(); // foo must be fully addressed
MyStuff.quux.newObj:
{
a:1,
b)
{
//do stuff
},
bar:3,
quux:
{
'3':'b',
'var':undefined
}
};
No comments yet.
Self-service commenting is not yet reimplemented after the Wordpress migration, sorry! For now, you can respond by email; please indicate whether you're OK with having your response posted publicly (and if so, under what name).