Class Extending Array

42 views
Skip to first unread message

Regis

unread,
Dec 6, 2013, 2:21:16 PM12/6/13
to mootool...@googlegroups.com
I want to create a class, similar to Elements (just, not with elements) which behaves like an array, but with additional methods on it that can manipulate the objects within (which are all of the same type). I'm aware that the magical "length" behavior wouldn't work as expected.

For example, is there any reason why something like this would not work as expected (as it seems to just fine):

var Numbers = new Class({ Extends: Array, increment: function(){ var self = this; self.forEach(function(n, i){ self[i]++; }); return self; } });
var n = new Numbers(); n.include(2).combine([3,4,5]).unshift(1); // [1,2,3,4,5]
n.increment(); // [2,3,4,5,6]


Aaron Newton

unread,
Dec 6, 2013, 2:22:50 PM12/6/13
to mootools-users
Why not just extend Array?


--
 
---
You received this message because you are subscribed to the Google Groups "MooTools Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mootools-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Regis Gaughan

unread,
Dec 6, 2013, 2:29:11 PM12/6/13
to mootool...@googlegroups.com
So there is a reason? ;)

In this example, I wouldn't want Array to implement "increment" as a
method -- only Numbers should have increment available (just as Array
doesn't have "addClass" but Elements does). The example may be
trivial, but if it was a list of more complex instances it becomes
more evident.
> You received this message because you are subscribed to a topic in the
> Google Groups "MooTools Users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/mootools-users/KBiU3Rq8SE8/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to

Aaron Newton

unread,
Dec 6, 2013, 2:31:58 PM12/6/13
to mootools-users
Well, you just wouldn’t call it on arrays that you were putting non-numbers into.

The only real reason is that your example extending array is really just creating a class with Array’s methods. You loose length and maybe some other goodness that makes Array iteration fast, for example. 

Marc Schmidt

unread,
Dec 6, 2013, 2:42:57 PM12/6/13
to mootool...@googlegroups.com

rgthree

unread,
Dec 6, 2013, 2:48:49 PM12/6/13
to mootool...@googlegroups.com
Makes sense. I was aware of the length issue, but iteration speed certainly makes sense too.

The real reason for a desirable subclass would be if this was distributable code we wouldn't want to "pollute" Array with an this example "increment" method.

rgthree

unread,
Dec 6, 2013, 2:51:07 PM12/6/13
to mootool...@googlegroups.com
This looks like a great read, thanks.
Reply all
Reply to author
Forward
0 new messages