2

Are there any pitfalls to code like this?

var Foo = function() {
    this.bar = function() { return 'bar'; };
};

var f = new Foo();
f[0] = 'hi';
f[1] = 'there';

Note that I'm creating a new function object with some misc properties, and then I'm treating the object like an array. Also how are the array values being stored in the object? Are 0 and 1 treated like property names?

mellowsoon
  • 22,273
  • 19
  • 57
  • 75
  • As long as you don't have a length-property no one will confuse your object with an array. – some Oct 22 '10 at 04:49

3 Answers3

8

Well, yes, 0, and 1 will be just two property names.

When you assign a property with the bracket notation, the expression between the brackets will be converted to String, and that string will be used as the property name.

In fact, even the indexes for real arrays are just that, properties:

var realArray = ['a'];
realArray.hasOwnProperty('0'); // true

The difference is that real array objects on every property assignment that correspond to a valid index[1], track internally the value of their length property.

That's one of the reasons why "subclassing" array objects is difficult, even with the new ECMAScript 5 extensions, or at the moment also with the proposed ECMAScript-Harmony Proxies 2 3, can't be completely done, in a stanard way.

That can be a problem, depending on how you plan to iterate the numeric properties.

If you enumerate the properties with the for-in statement, other members will appear, not just the numeric properties.

[1] A valid array index is any unsigned 32-bit integer in the range of 0 to (2^32)-1.

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • I'm a little surprised. That means there are no real arrays in Javascript. Only an object with a few array-type functions bolted on. – mellowsoon Oct 22 '10 at 04:45
  • @mellowsoon: That's absolutely right. All JavaScript objects, including arrays, are just a collection of properties. – casablanca Oct 22 '10 at 04:50
  • @mellowsoon, exactly, arrays are simply objects that have an special [`\[\[DefineOwnProperty\]\]`](http://ecma262-5.com/els5_html.htm#Section_15.4.5.1) internal method, (amongst other few peculiar characteristics). This internal method is used when you make a property assignment, and it takes care to track and compute the value of the `length` property. – Christian C. Salvadó Oct 22 '10 at 04:51
1

I think you might have problems if you try to loop through that with a for in loop; the loop will also get bar. There are ways around this, so you just have to be careful.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
1

If you want to extend Array behavious please use : Array.prototype.yourfunc = function()....

guilin 桂林
  • 17,050
  • 29
  • 92
  • 146