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...

4

1 回答 1

0

在您的代码中,您在构造函数中分配函数。你也可以在咖啡中做到这一点

myLib.container = ->
  things = []

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

  this

或者如果你真的想使用类语法

class myLib.container
  constructor: ->
    things = []
    @addItem = (item) -> things.push item
于 2013-03-26T11:14:25.147 回答