javascript - ES6 object.method 不是函数

标签 javascript oop ecmascript-6 es6-class p5.js

我有一个像这样定义的 ES6 类,并且有几个函数:

class Cell{
    constructor(i,j){
        this.i = i;
        this.j = j;
        this.alive = false;
        this.survives = false; //Made so not to change alive variabe mid-loop, also controls birthing of new cells
}

    update(grid){
       //Decide if this.survives is true or not
    }

    render(size){
        //Draw's a rectangle in the cell's location in a color based on this.alive
    }
}

还有一个 main.js 文件:

const h = 800; //Height
const w = 800; //Width
const s = 80;  //Size of squares
const rows = Math.floor(h / s);
const cols = Math.floor(w / s);
let cells = new Array(cols);
let isActive = false;


//A p5 function that is called once when the page is sketch is loaded
function setup() {
createCanvas(w, h);
for(let i = 0; i < cols; i++){
    cells[i] = new Array(rows);
    for(let j = 0; j < rows; j++){
        cells[i][j] = new Cell(i, j);
    }
}
}


//A p5 function that is called every frame
function draw() {
for(i = 0; i < cols; i++){
    for(j = 0; j < rows; j++){
        if(isActive === true){
            cells[i][j].update(cells);
            if(cells[i][j].survives){
                cells[i][j] = true;
            }else{
                cells[i][j] = false;
            }
        }
        cells[i][j].render(s);
    }
}
}

当我打开网页时,一切都会正常呈现,但是当我通过 Chromes 控制台将 isActive 设置为 true 时,我收到以下错误消息:

未捕获类型错误:cells[i][j].render 不是函数

我确保添加了对index.html中所有内容的引用,我没有对require()做任何花哨的事情。全部带有脚本标签

最佳答案

可能是因为在它上面你有:

if(cells[i][j].survives){
        cells[i][j] = true;  // <--- Overwriting the cell!
}else{
        cells[i][j] = false; // <--- Overwriting the cell!
}

您正在使用 bool 值覆盖单元格,而 bool 值没有 render 方法。

也许你的意思是?:

if(cells[i][j].survives){
        cells[i][j].alive = true;
}else{
        cells[i][j].alive = false;
}

尽管应该注意的是,这实际上应该写为:

cells[i][j].alive = cells[i][j].survives;

关于javascript - ES6 object.method 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833666/

相关文章:

javascript - ES6 Method Definition Shorthand 是否只创建一个函数对象?

PHP抽象类站点配置

c++ - vector 对象声明后的括号是什么意思?

javascript - 使用 ES6 类和 JSON 交换数据

javascript - 我怎样才能从对象中删除一个键,不可变,除非在您执行删除之前不知道键名?

javascript - jquery slider 在 WordPress 中的 Visual Composer 自定义短代码中不起作用

javascript - 如何在 nightwatch 中检查元素的文本长度是否大于 0?

javascript - Require.js 嵌套要求

javascript - 短手(呃)最小最大百分比?

javascript - 如何比较时间不使用 if else