TheGreyBearded
TheGreyBearded

Reputation: 357

ES6 object.method is not a function

I have an ES6 class that's defined like this and has a couple of functions:

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
    }
}

And a main.js file:

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);
    }
}
}

When I open the webpage everything renders normally but when I set isActive to true through chromes console I get the following error message:

Uncaught TypeError: cells[i][j].render is not a function

I made sure to add references to everything in index.html, I'm not doing anything fancy with require(). It's all with script tags

Upvotes: 0

Views: 485

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45745

Probably because right above it you have:

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

You're overwriting your cells with Boolean values, and Booleans don't have a render method.

Maybe you meant?:

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

Although it should be noted that this should really just be written as:

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

Upvotes: 1

Related Questions