Reputation: 2282
Currently I am working on Learning React and Redux. I have found a boilerplate, and I am working on looking through all of the example code. My problem is I don't completely understand what a lot of this ES6 syntax means.
What I have learned so far is that hello = () => "Hello";
would be equivalent to:
hello = function hello() {
return "Hello";
};
Then changing the above to hello = name => "Hello " + name;
would convert it to:
hello = function hello(name) {
return "Hello " + name;
};
That all makes perfect sense, basically it is just shortening it down so you don't have to write the function and its return statement. Yet, I have come across some syntax that I cannot rap my head around. It is as follows:
const mapActionCreators = {
increment: () => increment(1),
doubleAsync
}
The above code is converted to:
var mapActionCreators = {
increment: function (_increment) {
function increment() {
return _increment.apply(this, arguments);
}
increment.toString = function () {
return _increment.toString();
};
return increment;
}(function () {
return increment(1);
}),
doubleAsync: doubleAsync
};
I understand that () => increment(1)
in this case is being turned in to:
(function () {
return increment(1);
}),
Overall I guess my question is, how does increment:
get converted in to:
increment: function (_increment) {
function increment() {
return _increment.apply(this, arguments);
}
increment.toString = function () {
return _increment.toString();
};
return increment;
}
What is the meaning of the code?
Upvotes: 1
Views: 135
Reputation: 944533
Arrow functions capture the value of this
from the scope they are created in.
apply
lets you call a function and explicitly the value of this
in it.
The rest of the code is just feeding the correct this
to the function.
(And toString
is making sure that the right function gets stringified if you try to stringify the generated function).
Upvotes: 5