2

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?

2 Answers 2

2

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') };" 
Sign up to request clarification or add additional context in comments.

4 Comments

I am aware of x[1] == x.1. Is there a way to make x.i == x.myProperty()?
I've since addressed that in the post, remember, you can declare and pass functions around and you can call them and get their results, but you cannot call a function without ()
I guess I've not explained myself correctly. I know that functions can be asigned, but can a property like Python's, .NET's be done, instead of Java's getters and setters?
You want a C# style getter like: int MyProperty get { return computed_value; }; ? If so, no you cant do that
1

Currently Javascript Getters and Setters are possible only on

  • Firefox
  • Safari 3+
  • Opera 9.5+

Internet Explorer (in any of it versions) is lacking in this regard.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.