无法将对象推入数组 Javascript
我正在构建一款游戏,对于我的玩家,我有一个玩家类别。这个类定义了他们的名字、xpos、ypos 等。在我的主游戏循环中,我必须迭代所有当前玩家(它是多人游戏)并更新/绘制它们。
问题是,我不知道如何将玩家存储在游戏类中。我尝试在游戏类中执行此操作:
this.players = [];
然后:
game.players.push(new player(name));
但我收到此错误:
Uncaught TypeError: object is not a function
我一直认为我可以将对象作为数组元素,但显然不是。
有人可以建议更好的方法来做我想做的事吗?
I'm building a game, and for my players I have a player class. This class defines things like their name, xpos, ypos etc. In my main game loop, I have to iterate over all of the current players (it's multiplayer) and update/draw them.
Problem is, I don't know how to store the players in the game class. I tried doing this in the game class:
this.players = [];
And then:
game.players.push(new player(name));
But I get this error:
Uncaught TypeError: object is not a function
I always thought I could have objects as array elements, but apparently not.
Could someone advise a better way to do what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您定义了播放器构造函数吗?
某处需要有遵循以下格式的代码:
Have you defined the player constructor function?
There will need to be code somewhere that follows this format:
假设你有一个像这样的 Game 和 Player 类,
你可以这样做
Say you have a Game and Player class like this,
You can do
this
的上下文可能会发生您意想不到的变化。在您的班级中,请务必检查
this
的值是否正确。您可能需要使用闭包来确保您正在谈论您的课程。像这样:
The context of
this
is probably changing to something you don't expect.In your class, be sure to check the correct value of
this
. You probably need to use closures to ensure you are talking about your class.Like this:
想通了伙计们。我之前已经在另一个 JS 文件的代码中为玩家定义了一个变量。 检查您是否有类似的情况。
对于遇到此问题的其他人,请在尝试执行此操作之前
Figured it out guys. I already had a variable defined to player earlier on in my code in another JS file. For anyone else with this problem, check you don't have anything like
before you try and do this.