Reputation: 36852
I want to make a custom Array
object that recieves a number as index, and depending on the value of the index, it would return a computed value.
For example:
>>> var MyArray(2);
>>> MyArray[2];
4
>>> MyArray.2;
4
I know that for the showed example, I'm better of with a function, but I want to know if I can override the properties/index lookup for some things that are conceptualy arrays, but could need some computation.
I'm aware that x.1 == x[1]
, so what I need is to make a property in javascript.
I mean, make x.variable = x.myPropery()
, so everytime that I get the value of x.variable
, I recieve the return of x.myPorperty()
.
Is this even possible?
Upvotes: 2
Views: 149
Reputation: 36852
Currently Javascript Getters and Setters are possible only on
Internet Explorer (in any of it versions) is lacking in this regard.
Upvotes: 1
Reputation: 19446
variable[property] is the same as dot notation so you are doing MyArray.2, which is a variable, not a method that gets evaluated. You can't really do what you want without a method that either changes the property when it is assigned, or a method that computes the right value when you pull it out.
And no, you cannot override [], its simply dot notation, its not really an index that you can override
Re: your comment, Absolutely, you can do
var x = new Array();
x[1] = function () { alert('x') };
var myFunction = x[1];
x[1](); // alerts "x"
myFunction(); // alerts "x"
alert(x[1]); // alerts "function () { alert('x') };"
alert(myFunction); // alerts "function () { alert('x') };"
Upvotes: 2