9

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?

at.
  • 50,922
  • 104
  • 292
  • 461
  • Arrow functions retain context, but when you use `new` it will reset `this` and hence you will get error. If you want this to work, you can go back to ES5 hack `var self = this` – Rajesh Jul 22 '16 at 06:30
  • It's called an "arrow function", not a "fat arrow function" – Mulan Jul 22 '16 at 08:29

1 Answers1

9

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497