You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS/P5.js中MazeGen类display方法调用报错:TypeError: maze1.display is not a function

解决MazeGen类display方法调用报错的问题

问题出在MazeGen类的构造函数最后一行return this.maze;——JavaScript中,类的构造函数如果手动返回一个对象(这里的数组属于对象类型),会直接覆盖默认返回的类实例。所以maze1实际上是生成的二维数组,而非MazeGen的实例,自然没有display方法,导致报错TypeError: maze1.display is not a function。

修复方案

删除构造函数末尾的return this.maze;语句即可。类构造函数默认会返回当前实例,你已经把生成好的迷宫赋值给了this.maze,无需手动返回数组。

修改后的构造函数代码:

constructor(size) {
    console.warn('in funt')
    this.size = size
    this.maze = new Array(this.size);

    for (let i = 0; i < this.maze.length; i++) {
        this.maze[i] = new Array(this.size);
        for (let j = 0; j < this.maze.length; j++) {
            this.maze[i][j] = 0
        }
    }

    this.maze = this.PrimsAlgorithm()
    this.maze[1][0] = 3;
    this.maze[this.maze.length - 2][this.maze.length - 1] = 2;
    console.table(this.maze);
    // 移除手动返回数组的语句
}

后续使用说明

修改完成后,new MazeGen(11)会返回MazeGen类的实例,maze1.display()可以正常调用。同时类结构保持完整,你可以继续创建多个迷宫实例,比如:

let maze2 = new MazeGen(15);
maze2.display();

内容的提问来源于stack exchange,提问作者William ELLIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:31:06