嵌套函数不影响在全局范围内声明的二维数组中的对象

Nested functions not affecting objects in bidimensional array declared within global scope

提问人:Zabon 提问时间:4/26/2022 更新时间:4/26/2022 访问量:15

问:

我有一个充满 Cell 对象的二维数组。

我怎样才能使(和嵌套函数)使用每个单元格的上下文进行设置,以便我可以在方法中使用它?addToGrid(asset);cellsdraw

class Cell {
  constructor(value) {
     this.value = value;
  }
  
  makeAlive = () => {
    this.value |= (1 << 0)
  }

  incrementNeighbours = (num) => {
    this.value += 2;
  }
}

// Main
let cols;
let rows;
let cells;
let resolution = 2;
let infos = {};

s.setup = async () => {
  cols = 256;
  rows = 256;
  s.createCanvas(cols * resolution, rows * resolution);
  s.frameRate(60);

  cells = [...Array(cols)].map(x => Array(rows).fill(new Cell(0)));
  const loader = new AssetLoader();
  const asset= await loader.loadAsync('type', 'name');

  addToGrid(asset);
}

s.draw = () => {
    .
    .
    .
    // cells is not affected by addToGrid

}

const addToGrid = (asset) => {
  for (let i = 0; i < asset.length; i++) {
    .
    .
    .
    addStrToGrid(col, row, asset[i]);
  }
}

const addStrToGrid = (col, row, str) => {
  for (const c of str) {
      becomeAlive(col, row);
  }
}

const becomeAlive = (x, y) => {
  cells[x - 1][y - 1].incrementNeighbours();
  cells[x - 1][y].incrementNeighbours();
  cells[x - 1][y + 1].incrementNeighbours();
  cells[x][y - 1].incrementNeighbours();
  cells[x][y].makeAlive();
  cells[x][y + 1].incrementNeighbours();
  cells[x + 1][y - 1].incrementNeighbours();
  cells[x + 1][y].incrementNeighbours();
  cells[x + 1][y + 1].incrementNeighbours();
}

s.setup & s.draw分别来自库 p5.js !

JavaScript 函数 multidimensional-array scope this

评论

0赞 Bergi 4/26/2022
只是作为参数传递给所有函数?或者,引入一个具有属性的类,并使它们成为该类的方法。cellsGrid.cells
1赞 Bergi 4/26/2022
顺便说一句,没有做你想做的事情Array(rows).fill(new Cell(0))

答: 暂无答案