Skip to content

Instantly share code, notes, and snippets.

@micmarsh
Last active August 29, 2015 13:59
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 micmarsh/10781201 to your computer and use it in GitHub Desktop.
Save micmarsh/10781201 to your computer and use it in GitHub Desktop.
Fix Scoping in CoffeeScript
# While coffee script offers a "class" keyword, methods still aren't that closely
# associated with class instances. Include fixScoping(this) at the beginning
# of all of your constructors to make that class' methods well behaved by javascript standards
fixScoping = (instance) ->
for property, value of instance
do (property, value) -> #b/c javascript
if typeof value is "function"
instance[property] = (args...) -> value.apply(instance, args)
# obligatory contrived arithmetic-based example
class Adder
constructor: (@amount) -> fixScoping this
add: (num) -> num + @amount
addTwo = new Adder(2)
[1, 2, 3].map(addTwo.add) # => [3, 4, 5]
# "add" is still bound to its instance, none of that javascript-y silliness here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment