0

Sometimes I write my JS classes like this:

mylib.Container = function() {
  var things = [];

  // Returns the index of the image added
  this.addItem = function(item)
  {
    things.push(item)
  }
}
...
var c = new mylib.Container();
c.addItem(whatever);

I use "constructor-scoped" closured variables (like things) to avoid this scoping issues, and I am also using them in tight loops (like the ones used in requestAnimationFrame). These variables never bleed to the outside of the created fubject.

Is there a way to create and use such variables in CoffeeScript? I know that I have the @ivar notation which is shorter than this but something is telling me acessing a closured varmight still be faster...

Thomas W
  • 14,757
  • 6
  • 48
  • 67
Julik
  • 7,676
  • 2
  • 34
  • 48

1 Answers1

0

In your code, you're assigning function in the constructor. You can do that in coffee as well

myLib.container = ->
  things = []

  @addItem = (item) -> things.push item

  this

or if you really want to use the class syntax

class myLib.container
  constructor: ->
    things = []
    @addItem = (item) -> things.push item
Ven
  • 19,015
  • 2
  • 41
  • 61
  • If I do this using the class syntax, `things` will not be available outside of the constructor scope. Or is constructor scope the same as the function scope in my example? – Julik Mar 26 '13 at 13:10
  • That's why I added `@addItem` in the constructor – Ven Mar 26 '13 at 18:20