The fat arrow can be used in different settings but it somehow doesn’t
always bind to the instance I want.
The fat arrow can be used in different settings but it somehow doesn’t always
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The fat arrow binds at 3 occasions
1. When declaring a method
When the Coffeescript compiler encouters the following syntactical pattern
within a class declaration
This will yield the following code within the constructor of class A
That is the definition for that instance is overwriting the initial assignment
with a bound version of the function
2. When declaring a function within a method
When you define a function with a fat arrow within a method the Coffeescript compiler
automatically creates a closure and and shadows this of the outer method into the variable
_this. Any reference to @ within the inner function will use the variable _this
in the generated javascript code
And this is the corresponding Javascript
A definition of a function without the fat arrow doesn’t create that closure for you.
3. When declaring a function in global context
If you define a free floating function (meaning as a method in a class and not within another function/method) just like this
Then the corresponding Javascript will look like this
The interesting thing here again is that this is being assigned to _this which enables the definition of foo to close over _this.
The important part however is that this is always the global context of your execution environment. If you are in the browser it will be the window object. If you are running node.js it will be the module you are just running.
Warning: You shouldn’t define any function accessing your global context anyway. This calls for trouble.