array like objects

Brendan Eich brendan at mozilla.com
Tue Dec 15 07:03:23 PST 2009


On Dec 15, 2009, at 4:51 AM, P T Withington wrote:

> On 2009-12-08, at 13:10, Mike Samuel wrote:
>
>> All true.  And yet it is not uncommon.  See the bottom of this email
>> for a quick survey of a number of libraries' uses of the array-like
>> concept.
>
> FWIW, Here is the (separately/simultaneously invented) definition  
> from OpenLaszlo:
>
>  function isArrayLike (obj:*):Boolean {
>    if (obj && ((obj is Array) || (obj['length'] != (void 0)))) {

ES4-ish "is" operator -- this must be LZX-JS?


>      var ol = obj.length;
>      return ((typeof(ol) == 'number' || ol is Number) &&
>              ((ol|0) === ol) &&
>              (ol >= 0));

Could combine the last two using >>>:

js> (-1|0)===-1
true
js> (-1>>>0)===-1
false


>    }
>    return false;
>  }
>
> This only shows up in the debugger, and it is used to heuristicate  
> when inspecting an object whether to portray it as an Array  
> (possibly with non-numeric properties), or as an Object.  It's an  
> acknowledgement that users do create objects that they think of as  
> arrays.  OTOH, we don't do any magic beyond that.  If a user intends  
> an object to be treated as an array, they use Array operations on it  
> (including `for`, not `for in`).
>
> I once had the vain hope that I could say:
>
>  function MyArray () {}
>  MyArray.prototype = [];
>
> to create my own subclasses of Array.  That might have lessened the  
> need for isArrayLike.

If only internal methods were looked up by their (unnameable in the  
language [1]) names, instead of being accessed via [[Class]] (which is  
never delegated). Then lack of a custom [[Put]] in a (new MyArray)  
would let the prototype [[Put]] shine through, but receive the (new  
MyArray) instance as the object whose .length should be updated to be  
one greater than the highest index.

But [[Class]] is a lightly abstracted vtable pointer; more's the pity.

/be

[1] http://wiki.ecmascript.org/doku.php?id=strawman:names


More information about the es-discuss mailing list