Dealing With 'immediately Invoking' Functions As Object Properties

- 1 answer

In a small React project I made, I wanted to initialise an array in getInitialState by calling a function. The arguments refer to two other properties in getInitialState. This is how I did it:

  getInitialState() {
    return {
      numRows: 55,
      numCols: 47,
      arrInit: function(){
        this.grandArr = this.initBlank(this.numRows, this.numCols);
        return this;
    }.arrInit(); //Creates `grandArr` in the `state`

(this.initBlank is a method in the component that returns an array.)

The way of chaining arrInit looks pretty messy. Is there a better/cleaner way to do it?



It looks like you're expecting this to refer to both the state object AND the component. I would do the setup and then return the object you want:

getInitialState() {
  const numRows = 55,
        numCols = 47,
        grandArr = this.initBlank(numRows, numCols);

  return {numRows, numCols, grandArr};