javascript - 将 'immediately invoking' 函数作为对象属性处理

标签 javascript function object reactjs state

在我制作的一个小型 React 项目中,我想通过调用函数来初始化 getInitialState 中的数组。这些参数引用了 getInitialState 中的另外两个属性。我就是这样做的:

  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 是组件中返回数组的方法。)

链接arrInit的方式看起来相当困惑。有更好/更干净的方法吗?

最佳答案

看起来您希望 this 引用 state 对象和组件。我会进行设置,然后返回您想要的对象:

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

  return {numRows, numCols, grandArr};
}

关于javascript - 将 'immediately invoking' 函数作为对象属性处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797968/

相关文章:

javascript - Doxygen 带有 HTML 按钮,点击后会更改文本

javascript - 单击按钮获取 li 的索引

c++ - 为什么malloc前面有(void*)?

bash - shell脚本: Indirect recursion doesn't work as expected (too many repetitions)

php - 什么是 PHP 中的对象克隆?

C#对象和内存管理

javascript - 根据变量值动态添加类到表中

javascript - 等待多个 $.getJSON 完成

c - 向函数传递指针

python - 如何测试 python 中的两个对象是否相等?