有没有办法在数组中调用“新”对象构造函数,这些构造函数都包含在一个对象中?

Is there a way to call a "new" object constructor inside of an array all housed in an object?

提问人:J.F. 提问时间:7/20/2023 最后编辑:RF1991J.F. 更新时间:7/20/2023 访问量:37

问:

如果将对象同时具有对象构造函数和数组,则会同时调用对象构造函数的“new”,从而出现一条错误消息,指出未定义对象构造函数名称。

这是我的 JavaScript 代码:

var game = {
  //constructor function for every block type
  blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    //name is just for reference
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    //if collision would be on or off
    this.passable = passable;
  },

  blockTypes: [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)],

};

错误消息说

blockType 未定义

相反,当我放时,有错误消息,new game.blockType

游戏未定义

我是声明或称事情是错误的,还是有办法解决这个问题?

JavaScript Arrays 对象 构造函数

评论

1赞 M0nst3R 7/20/2023
[new blockType(...在对象仍在定义时当场调用,因此尚未定义。您可以在定义对象后对其进行定义。

答:

2赞 trincot 7/20/2023 #1

new blockType引用具有该名称的变量,但没有此类变量。请注意,这是一个属性,而不是一个变量。game.blockType

new game.blockType在分配一个值之前进行计算,因此也无法正常工作。game

有很多解决方案。例如,首先定义不带第二个属性,然后添加它:game

var game = {
  //constructor function for every block type
  blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    //name is just for reference
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    //if collision would be on or off
    this.passable = passable;
  },

};

game.blockTypes = [new game.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];

console.log(game);

另一种解决方案是首先创建为(局部)变量:blockType

var game = (() => {
  //constructor function for every block type
  const blockType = function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    //name is just for reference
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    //if collision would be on or off
    this.passable = passable;
  };
  const blockTypes = [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];
  return {blockType, blockTypes};
})(); // Immediately invoked function expression

console.log(game);

评论

0赞 J.F. 7/20/2023
谢谢。第一种方法很好地解决了我的问题。