在 javascript 对象字面量中直接使用 `new this.blocktype` 或 `new blocktype` 初始化数组会导致引用错误,因为构造函数尚未作为变量存在,且对象本身还未完成赋值;需通过分步定义、闭包封装或延迟初始化等方式解决。
在 JavaScript 中,当试图在一个对象字面量(object literal)内部直接用 new blockType(...) 创建实例并存入数组(如 blockTypes: [new blockType(...)])时,会遇到经典的 “blockType is not defined” 错误。根本原因在于:对象字面量的属性值是在对象创建过程中逐个求值的,而此时 blockType 仅是该对象的一个属性名,并未作为独立变量或可访问的标识符存在于当前作用域中。更进一步,若尝试写成 new game.blockType(...),则会报 “game is undefined” —— 因为 game 变量的赋值操作(var game = { ... })尚未完成,game 在右侧表达式执行时尚未声明完成,无法被引用。
先定义空对象(含构造函数),再单独添加依赖构造函数的属性:
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.blockType 可安全访问
game.blockTypes = [new game.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];✅ 优点:语义明确、调试友好、符合直觉;适用于大多数模块化场景。
利用立即执行函数表达式(IIFE)在局部作用域中定义构造函数与实例,再返回干净的对象:
var game = (function() {
// 构造函数仅在此闭包内可见
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;
}
return {
blockType: blockType,
blockTypes: [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)]
};
})();✅ 优点:避免污染外部作用域;blockType 不会意外被全局覆盖;适合构建可复用的游戏资源模块。
将实例化逻辑推迟到首次访问时执行(例如使用 getter):
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;
},
get blockTypes() {
// ✅ 首次访问时才创建,确保 this.blockType 可用
const instances = [new this.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];
Object.defineProperty(this, 'blockTypes', { value: instances }); // 缓存结果
return instances;
}
};⚠️ 注意:此方式适合只读场景;若需在初始化后修改 blockTypes 数组,请改用普通属性 + 显式初始化函数。
通过合理组织初始化顺序或作用域结构,即可安全、清晰地在对象中封装构造逻辑与其实例集合。