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

JavaScript对象内数组调用构造函数报错,求解决方法

问题原因

当你在对象字面量game内部初始化blockTypes时,game对象还未完成创建(赋值流程尚未结束),所以直接用game.blockType会提示game未定义;而blockType是game的内部属性,并非全局变量,直接调用new blockType自然找不到该函数。

修复方法

以下是几种可行的解决方式:

方法1:先定义构造函数,再挂载到game对象

把构造函数单独提取出来定义,再赋值给game的属性,创建实例时直接引用这个已存在的构造函数:

// 先定义构造函数
function blockType(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
  this.name = name;
  this.imageX = imageX;
  this.imageY = imageY;
  this.width = width;
  this.height = height;
  this.xEffect = xEffect;
  this.yEffect = yEffect;
  this.passable = passable;
}

var game = {
  blockType: blockType,
  blockTypes: [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)]
};

方法2:先创建game基础对象,再单独初始化blockTypes

先完成game的基础结构赋值,待game完全创建后,再给blockTypes属性赋值,此时可正常引用game.blockType:

var game = {
  blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    this.passable = passable;
  }
};

// game已初始化完成,可正常调用构造函数
game.blockTypes = [new game.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];

方法3:用初始化方法内部引用构造函数

如果blockType不需要在外部调用,可以把blockTypes的初始化逻辑封装成方法,通过this访问对象内部的构造函数:

var game = {
  blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    this.passable = passable;
  },
  initBlockTypes: function() {
    this.blockTypes = [new this.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];
  }
};

// 调用初始化方法完成blockTypes赋值
game.initBlockTypes();

内容的提问来源于stack exchange,提问作者J.F.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:13:12