Skip to content

Instantly share code, notes, and snippets.

@wereHamster
Created September 3, 2011 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wereHamster/1191791 to your computer and use it in GitHub Desktop.
Save wereHamster/1191791 to your computer and use it in GitHub Desktop.
class Unit
@create: (options) ->
# This is the object which will hold the private data.
privData = {}
# We create a new unit and pass it the privData object.
unit = new Unit privData, options
# Wrap all methods and pass privData as the first argument. This incurs
# minimal overhead because we only have to create wrappers while the
# actual method stays the same and can be shared between instances.
for name, method of Unit.prototype
unit[name] = ->
args = Array.prototype.slice.call arguments
args.unshift privData
method.apply @, args
# Return the new object.
return unit
# Here you can put private data into privData and nobody will have access to
# it. Properties added to @ will be publicly readable and writeable.
constructor: (privData, options) ->
privData.x = options.x || 0; privData.y = options.y || 0;
@publicData = 42
move: (privData, x, y) ->
privData.x += x; privData.y += y;
console.log "Moved to #{privData.x} #{privData.y}"
console.log @publicData
unit = Unit.create { x: 1, y: 2 }
unit.publicData = -1
unit.move -2, 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment