5

I am trying to use the extends for array ..what should I put in the constructor..Here is the code

class List extends Array
  constructor: ()->
      super arguments
      this

list = new List("hello","world")
alert list[0]

Doesn't seem to work..

1
  • Do a bit of Googling for "javascript subclassing array", it doesn't really work period. Commented Mar 13, 2012 at 16:50

2 Answers 2

5

There is no easy way to "inherit" from the array prototype. You should use composition , i.e.

    class List
      constructor: ()->
          this.array = new Array(arguments);
      getArray   :()->
          this.array


list = new List("hello","world")
alert list.getArray()[0]

or you will spend your time implemented complicated solutions that will fail as soon as you try to parse the array or access its length value.

more on the issue :

http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

Sign up to request clarification or add additional context in comments.

Comments

-1

I haven't been using coffee script lately, so this is just a guess, but maybe something like:

class List extends [].prototype

might work?

EDIT: Per "mu is too short"'s comment, it seems the problem isn't coffee script related at all. You might find this related SO post useful, as the selected answer provides two possible solutions to this problem: Is this a reasonable way to 'subclass' a javascript array?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.