Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 521
slyprid Avatar asked Nov 10 '09 21:11

slyprid


People also ask

Can [] operator be overloaded?

where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .

What does overloading the [] operator do?

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

Which operator is overloaded in JavaScript?

With this proposal, operators can be overloaded on certain JavaScript objects that declare themselves as having overloaded operators. The following operators may have overloaded behavior: Mathematical operators: unary + , - , ++ , -- ; binary + , - , * , / , % , **

How do you overload a function in JavaScript?

JavaScript does not support function overloading natively. If we will add functions with the same name and different arguments, it considers the last defined function.


1 Answers

You can do this with ES6 Proxy (available in all modern browsers)

var handler = {     get: function(target, name) {         return "Hello, " + name;     } }; var proxy = new Proxy({}, handler);  console.log(proxy.world); // output: Hello, world 

Check details on MDN.

like image 88
average Joe Avatar answered Oct 24 '22 06:10

average Joe