Search code examples
javascriptoperator-overloading

How would you overload the [] operator in javascript


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.


Solution

  • This answer is outdated as of ES6. See average Joe's answer for an answer using new features in ES6. However, this answer is still true for browsers that lack ES6 support.

    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.