Last active
August 29, 2015 14:04
-
-
Save ronny/d4ccc41322d737dcfaf2 to your computer and use it in GitHub Desktop.
The main difference between fat and thin arrows for instance methods 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
| # Try running this in http://coffeescript.org 's "Try CoffeeScript" tab while having the DevTools console open. | |
| class Foo | |
| thin: (arg) -> | |
| console.log 'thin', this, @value?(), arg | |
| fat: (arg) => | |
| console.log 'fat', this, @value?(), arg | |
| value: -> | |
| 'foobar' | |
| foo = new Foo | |
| # The behaviour is exactly the same in this case: | |
| foo.thin('plain') | |
| foo.fat('plain') | |
| # The behaviour is different when the context of `this` is changed. | |
| # This commonly happens when the functions are used as callbacks. | |
| # Sometimes we use `_.bind`, like below, to achieve that with | |
| # thin-arrow instance methods: | |
| # | |
| # $('#thin').on 'click', _.bind(foo.thin, foo) | |
| # | |
| # When you run the following, notice that in thin's console log, | |
| # the value of `this` is `window` (hence `@value` is `undefined`), | |
| # and that in fat's console log, the value of `this` is `foo`. | |
| foo.thin.apply(window, ['applied']) | |
| foo.fat.apply(window, ['applied']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment