Subclassing an array and array methods

Axel Rauschmayer axel at rauschma.de
Sat Nov 12 10:20:31 PST 2011


>> I misunderstood the problem: I thought there was something peculiar about an array instance (the first object in the prototype chain), but it’s about the Array constructor not being invocable as a function (right?).
> 
> I'm not sure what you mean about "not invocable as a function".  
>   ArraY(1,2,3,4)
> works just fine an creates an array instance.

Sorry, I meant: always produces a new instance, even when invoked as a function.

>> Wouldn’t it be easier to introduce a generic method Array.prototype.init() that behaves like quirk-free Array.prototype.constructor()?
>> 
>> Use case 1: Create an array subtype:
>>   let SubArray = Array <| function(...args) {
>>       super.init(...args); // instead of super.constructor(...args)
>>   }
> 
> the problem is that the "specialness" of arrays is mostly that they have their own alternative definition of [[DefineOwnProperty]].  By the time you reach the init call, the new object has already been created with the default [[DefineOwnProperty]]  behavior.  It isn't clear, that it is possible or reasonable to change such internal behaviors after an object is created. myProto<| [ ] avoid the problem by forcing creation (via [ ] ) of an object with the special array [[DefineOwnProperty]].

Right, I overlooked that: You need to “intercept” elements being set/added, in order to update `length`.

Then init() would not make sense at all. I didn’t know that array instances were special, I assumed the specialness was all in Array.prototype.

> There are potentially other ways around this problem.  For example, there could be a well know private name property that could be attached to a constructor that would force |new| to create instances that use the Array internal methods.

That would be a great solution! Or, if one could move the specialness from array instances to Array.prototype.

It seems that the reformed [] would also allow one to create an Array variant (e.g. called Sequence, List, or Vector) that is more amenable to subtyping/extension/subclassing.


>> Whatever the solution, it’s obviously applicable to Date, Error, etc., as well.
> 
> Those are actually easer to make subclassable because they don't redefine any of the internal methods.  All that is needed is to convert their private state into private named properties.  That's already on my todo list.

And you’d need a way to invoke their constructor as a function, on an existing instance.

-- 
Dr. Axel Rauschmayer
axel at rauschma.de

home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111112/dc5e4806/attachment-0001.html>


More information about the es-discuss mailing list