Javascript TypeError,无法访问对象的方法

标签 javascript object typeerror p5.js

我正在使用 p5.js、node.js 和 socket.io 在浏览器中制作一个小型多人游戏。名为“player”的对象从一个客户端传递到另一个客户端以同步两个客户端。这对于不依赖方法调用的其他代码来说效果很好。但现在我还想访问播放器对象中存储对象的方法,它不再起作用了。

这将是存储两个客户端之间的所有变量和包含对象的数组的对象:

var player = {
  structures: []
};

现在,如果我向其中添加一个名为“campfire”的对象,如下所示:

player.structures.push(new campfire(mouseX,mouseY));

并尝试调用对象campfire的draw()方法,如下所示:

class campfire {
constructor(x,y){
    this.scale = 40;
    this.x = x;
    this.y = y;
    this.maxLevel = 3;
    this.button = new button(this.x, this.y+50, this.x-50, this.y-70, upgrade, upgrade_hover, this);
    this.show_upgrade_button = true;
}

draw(){
    switch(player.campfire.level){
        case 1: image(fire, this.x, this.y, this.scale, this.scale);break;
        case 2: image(campfire_2, this.x, this.y, this.scale, this.scale);break;
        case 3: image(campfire_3, this.x, this.y, this.scale, this.scale);break;
        default: console.log("cant upgrade, this shouldn't happen.");
    }
    if(this.show_upgrade_button){
        this.button.draw();
    }
}

trigger(){      
    if(player.campfire.level + 1 <= this.maxLevel && this.show_upgrade_button == true){
        this.button.trigger();
    }
}}

使用

player.structures[i].draw();

控制台(客户端未将对象“campfire”推送到数组“结构”中)打印以下错误:

gui.js:38 Uncaught TypeError: player.structures[i].draw is not a function

将篝火对象推送到数组的客户端能够进行draw()调用并且不会打印错误消息。但是,尚未将对象推送到数组的另一个客户端无法使用该方法并打印出错误,即使它们共享相同的“玩家”对象。奇怪的是,打印出错误的人仍然能够访问 Campfire 对象的所有变量,因此它似乎只影响方法。

我找到的关于此的唯一资源是这篇文章 https://airbrake.io/blog/javascript-error-handling/x-is-not-a-function-typeerror 我尝试将函数重命名为draw = function(){}和campfire.prototype.draw = function(){},但这对我来说没有什么区别。我认为函数没有声明对吧?这将是我现在唯一可能的解释。

感谢您花时间阅读我的问题!

编辑:这是该项目的链接:https://github.com/Mayhoon/Multiplayer-Browsergame

最佳答案

我认为你的问题更多是在设计层面。 Socket.io(或任何其他同步库)并不是真正要来回推送整个代码片段。在你的例子中,这就是篝火的功能。

我建议只来回插入state。玩家有锤子吗?玩家有多少条生命?玩家有篝火吗?换句话说,只同步不断变化的数据。

由于篝火的功能(抽奖功能)对于所有玩家来说都是相同的,因此无需每隔几秒就来回推送该代码!实在是太低效了!

相反,当您的同步对象表明玩家有篝火时,您可以在客户端中创建篝火实例。

在代码中可能看起来像这样(只是一个想法):

同步socket.io对象

var player = {
  structures: {campfire:true}
};

客户端代码

// create campfire instances, tell the campfire which player it belongs to
if(player.structures.campfire) {
    let cf = new Campfire(player)
    cf.draw()
}

注意:socket.io 很可能会删除可执行代码

关于Javascript TypeError,无法访问对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55553724/

相关文章:

javascript - 在 webpack 的 require 中强制重新缓存 JSON 文件

javascript - 如何将 anchor 链接列表转换为选择下拉列表,在选项更改时操作更改选项卡?

javascript - ClojureScript 中 String.prototype.startsWith 的实现

Java 对象转换行为异常

python - Django 抛出 TypeError : _wrapped_view() missing 1 required positional argument: 'request'

python - len 和 str.splitlines() 的奇怪行为

javascript - 将 HTML 内容加载到 DIV 后调整颜色框的大小

javascript - 如何在 Vue 3 中替换 this.$parent.$emit?

javascript - forEach 方法似乎跳过一个条目

python - ZMQ 套接字类型错误 : unicode strings only Error: is there a fix?