Design principles for extending ES object abstractions

Brendan Eich brendan at mozilla.com
Fri Jul 8 18:21:12 PDT 2011


On Jul 8, 2011, at 5:53 PM, David Herman wrote:

> I think I still haven't fully grokked what <| means on array literals, but could it also be used to "subclass" Array? For example:
> 
>     function SubArray() {
>         return SubArray.prototype <| [];
>     }
> 
>     SubArray.prototype = new Array;
> 
> I'm not sure what Array.prototype methods would or wouldn't work on instances of SubArray.

Instances of SubArray must mean (new SubArray) results, but those are indeed true Array instances. They simply have a prototype chain that has been extended:

a = SubArray(); // or new SubArray

Object.getPrototypeOf(a) -> SubArray.prototype (which is an Array)
Object.getPrototypeOf(SubArray.prototype) -> Array.prototype
and Array.prototype of course delegates to Object.prototype

This allows new methods to be added to SubArray.prototype.

Sometimes people try to make a new Array instance be the prototype of some other object:

js> var o = Object.create([])
js> o[2] = 0
0
js> o.length
0
js> o[1] = 1
1
js> o[0] = 2
2
js> o.toString()
""
js> o.slice(0,1)
[]
js> o.length = 3
3
js> o.slice(0,1) 
[2]
js> o.sort(function(a,b){return a-b}).toString()
"0,1,2"
js> o.reverse().toString()
"2,1,0"

Note the lack of automagic length maintenance in this case. I think this is all per ES5.

/be
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110708/ad44664b/attachment.html>


More information about the es-discuss mailing list