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?
Well, yes,
0, and1will 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:
The difference is that real array objects on every property assignment that correspond to a valid index[1], track internally the value of their
lengthproperty.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-instatement, 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.