3

In coffee script i have this little code snippet.

class Collection

  construct:(@collection=[])

Now i want to access that object as if it was an array but i want to get the collection variable when i do so. In other languages i would implements an ArrayAccess of some type and code the next, current etc methods

obj= new Collection([1,2,3])

obj[0] # this should equal 1 

How can i do this in javascript or coffeescript either will do

1 Answer 1

1

That's impossible. You would need some kind of proxy for that. There is no "ArrayAccess" declaration feature, as bracket notation is just property access on your Collection instance (like obj["collection"]).

Instead, you can:

  • implement a getter function, like

    class Collection
      construct:(@collection=[])
      at: (i) ->
        @collection[i]
    
    obj.at 0 # 1
    
  • use the Collection object itself as a holder of the elements (like e.g. jQuery does it). You loose the native array features, though. You might even subclass Array to some extent (.length does not update automatically).

    class Collection
      constructor: (col = []) ->
        @length = 0
        for el in col
          Array::push.call(@, el)
    
    obj[0] # 1
    
Sign up to request clarification or add additional context in comments.

2 Comments

The at is a good idea. maybe coupled with an all for foreach loops.
@Lpc_dark: each please, all is a common synonym for every

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.