views:

656

answers:

3

I can't seem to find the way to overload the [] operator in javascript. Anyone out there know?

I was thinking on the lines of ...

MyClass.operator.lookup(index)
{
     return myArray[index];
}

or am I not looking at the right things.

Thanks in advanced

+4  A: 

So you're hoping to do something like var whatever = MyClassInstance[4]; ? If so, simple answer is that Javascript does not currently support operator overloading.

XHR
A: 

I don't know the right answer, but I would assume that you'd need to define both the getter AND the setter. In c#, you'd do this with something like the following:

MyClass.operator.lookup(index)  
{  
    get { return myArray[index]; }  
    set { myArray[index] = value; }  
}
uosɐſ
If you "don't know the right answer", don't answer.
LiraNuna
And, even though I'm not sure about the full answer, I did find this older page suggesting that overloading might be possible. http://www.mozilla.org/js/language/js20-2000-07/libraries/operator-overloading.html
uosɐſ
@LiraNuna, Seconded.
Matt Baker
Even if Jason posted the wrong answer, I don't believe he should refrain from posting. Even a wrong answer will help you get closer to the correct answer, even.
strager
That's right strager, and we will all vote him down for it :-)
Frew
+13  A: 

You can't overload operators in JavaScript.

It was proposed for ECMAScript 4 but rejected.

I don't think you'll see it anytime soon.

Peter Bailey
Aight thanks, no wonder couldn't find anything =D