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.
where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .
The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.
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 + , - , * , / , % , **
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With