I have a simple function (within a React component):
getInitialState: function() {
return {
text: this.props.text
}
}
But I want to fat arrowify it:
getInitialState: () => {
text: this.props.text
}
except I get an error, because a {
after a fat arrow means a block of code that returns undefined (unless you explicitly return
something). At least that's what I thought at first. But I think this
is being bound now to that fat arrow function and now this.props
is undefined
.
So I try this:
getInitialState: () => new Object({
text: this.props.text
})
But I get the same error, this.props
is undefined.
So I guess I have 2 issues I'm curious about. First, what's the idiomatic way to return an object from a simple statement fat arrow function? Second, how do I return an object that has a reference to the this
object of the surrounding context?
The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console. log(raspberry.name);
Arrow functions can automatically return a value so the return keyword can sometimes be omitted (more below) When there is only one parameter, the parameter parentheses () can be removed.
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.
You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.
Surround it with parenthesis, like this
getInitialState: () => ({
text: this.props.text
})
without the parenthesis, the object literal looks also like a JavaScript block with a label called text
in it. Since it is ambiguous, the SyntaxError is thrown. But when you surround it with ()
, JavaScript knows that it is an Object literal.
I think this is being bound now to that arrow function
Arrow functions don't have this
. When this
is encountered in an arrow function, it will go to previous level to see if this
is available there and use that. You can confirm that, like this
(function Test1() {
console.log(this);
(() => console.log(this))();
}).bind({a: 1})();
would print
{ a: 1 }
{ a: 1 }
In your case, this
will refer the this
object of the function in which it is declared, not the object itself.
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