The fat arrow can be used in different settings but it somehow doesn't always bind to the instance I want.
Basically in the Arrow function, this always represents the object in which the arrow function is defined. Arrow syntax automatically binds this to the surrounding code's context under the hood. In the Arrow function, it is not dependent on how they are invoked but it closes on the surrounding context.
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
Arrow Functions — also called “fat arrow” functions, are relatively a new way of writing concise functions in JavaScript. They have been introduced by the ECMAScript 6 specifications and since then become the most popular ES6 feature.
The fat arrow binds at 3 occasions
When the Coffeescript compiler encouters the following syntactical pattern within a class declaration
class A
somemethod: (paramlist) =>
This will yield the following code within the constructor of class A
this.somemethod = __bind(this.somemethod, this);
That is the definition for that instance is overwriting the initial assignment with a bound version of the function
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
somemethod: ->
=> @someCall()
And this is the corresponding Javascript
A.prototype.somemethod = function() {
//_this references this
var _this = this;
return function() {
//and _this is now used within the inner function
return _this.someCall();
};
};
A definition of a function without the fat arrow doesn't create that closure for you.
If you define a free floating function (meaning as a method in a class and not within another function/method) just like this
foo = => @bar
Then the corresponding Javascript will look like this
var foo,
_this = this;
foo = function() {
return _this.bar;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With