Subclassing an array and array methods
Allen Wirfs-Brock
allen at wirfs-brock.com
Fri Nov 11 11:07:52 PST 2011
On Nov 11, 2011, at 10:52 AM, Axel Rauschmayer wrote:
> Got it, related to what you solve in generic classes with This-types (covariance vs. contravariance...).
>
> // assume |this| is the source collection
> if (this[Array.derivedArrayKey]) A = this[Array.derivedArrayKey](); else A = [ ];
>
> Another possibility:
>
> if (this[Array.derivedArrayKey]) {
> A = this[Array.derivedArrayKey]();
> } else if (typeof this.constructor === "function") {
> A = new this.constructor();
In Smalltalk the default implementation of species is:
species
^self class
which is pretty much the moral equivalent of: this.constructor.
However, that might introduce backwards compatibility issues for existing code which has constructors but currently always produces Array instances from these functions.
> } else {
> A = [ ];
> }
>
> Creating a subclass this way (i.e., using @derivedArrayKey) produces code whose meaning is more obvious (to me) than the code below.
I just wanted to dash out the most directly extensions of Jake's original code that would exhibit the concept. Ultimately, it's a matter of defining a method using which ever formulation you prefer (and which gets adopted into the language)
>
>>>> function createArraySubclass(proto,...values) {
>>>> return proto <| [...values].{
>>>> [Array.derivedArrayKey](){return proto<| [ ]}
>>>> }
>>>> }
Allen
More information about the es-discuss
mailing list