0

I'm trying to overload JavaScript's indexing operator. I tried doing it like this:

var obj = {};
obj.[] = function(i) {
}

…but the above code failed; I think the compiler doesn't support overloading the index operator. I really need such a method; is there any way to implement it?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
coollofty
  • 339
  • 4
  • 15
  • 2
    Why do you need this? What are you trying to achieve? –  Sep 29 '13 at 03:51
  • 1
    If I had to venture I guess I think the OP wants to be able to do `obj[10]` and have it call his function with `i = 10`. [This blog post might help.](http://www.bennadel.com/blog/2292-Extending-JavaScript-Arrays-While-Keeping-Native-Bracket-Notation-Functionality.htm) – Mike Sep 29 '13 at 03:52

2 Answers2

1

Operator overloading is not possible in javascript.

Check the answer given here https://stackoverflow.com/a/1711405/1903116

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

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.

rockerest
  • 10,412
  • 3
  • 37
  • 67