Last active
August 29, 2015 13:59
-
-
Save micmarsh/10781201 to your computer and use it in GitHub Desktop.
Fix Scoping in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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