【问题标题】:ES6 object.method is not a functionES6 object.method 不是函数
【发布时间】:2017-10-05 15:08:24
【问题描述】:

我有一个这样定义的 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 时,我收到以下错误消息:

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

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

【问题讨论】:

  • 嗯,truefalse 的值确实没有这样的方法。

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


【解决方案1】:

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

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

您正在使用布尔值覆盖单元格,而布尔值没有 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;

【讨论】:

  • 我的天啊,看到你的初学者代码中暴露出这样一个愚蠢的错误,真让人心痛
  • @TheGreyBearded Np,它发生了。请注意,您可以通过在发生错误的上方写入console.log(type(cells[i][j])) 来立即解决此问题。每当您收到“不是方法错误”时,这可能意味着您的对象与您预期的类型不同。如果这解决了您的问题,请打勾将其标记为已解决,如果对您有帮助,请点赞。
猜你喜欢
  • 2016-08-11
  • 1970-01-01
  • 2016-07-03
  • 2014-12-05
  • 1970-01-01
  • 2019-10-25
  • 2017-01-04
  • 2017-04-28
  • 2019-03-11
相关资源
最近更新 更多