It's not so much that Javascript doesn't support overloading the indexing operator (I haven't looked into it, so I have no idea, but I bet there's a way). It's that [
is not a valid first character for a property name, so the entire name becomes invalid.
In case you're interested, the JIT compiler in Firefox 24 threw:
SyntaxError: missing name after . operator
obj.[] = function(i) {
^
You can't reference invalid property names with the .
syntax. Regardless of how you want to use the syntax you've described above, you will ALWAYS come back to this issue. []
is not a valid property name, so it will always fail on an object.
As others have mentioned, you can use the bracket syntax to reference any invalid name, like obj["[]"]
.
Here's a cut and paste from Mathias Bynens' "Javascript Identifiers".
An identifier must start with $, _, or any character in the Unicode
categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”,
“Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”,
or “Letter number (Nl)”.
The rest of the string can contain the same characters, plus any
U+200C zero width non-joiner characters, U+200D zero width joiner
characters, and characters in the Unicode categories “Non-spacing mark
(Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or
“Connector punctuation (Pc)”.
That’s it, really.