Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS和PHP中需要相同的类,正确的处理方法是什么?_Javascript_Php_Json - Fatal编程技术网

Javascript 在JS和PHP中需要相同的类,正确的处理方法是什么?

Javascript 在JS和PHP中需要相同的类,正确的处理方法是什么?,javascript,php,json,Javascript,Php,Json,我需要在JS和PHP中提供大量类(在JS中用于GUI,在PHP中用于代码执行) 我不愿意把所有的类都写两遍,因为即使每个类本身都很小,但它们却很多 到目前为止,我只做了JS方面的工作: 例子 function BaseLaser(parentId, arc1, arc2, arc3, arc4){ this.parentId = parentId; this.arc1 // etc this.draw = function(){ //draw on canv

我需要在JS和PHP中提供大量类(在JS中用于GUI,在PHP中用于代码执行)

我不愿意把所有的类都写两遍,因为即使每个类本身都很小,但它们却很多

到目前为止,我只做了JS方面的工作:

例子

function BaseLaser(parentId, arc1, arc2, arc3, arc4){
    this.parentId = parentId;
    this.arc1 // etc
    this.draw = function(){
       //draw on canvas
    }
}


function HeavyLaser(parentId, arc1, arc2, arc3, arc4){
    BaseLaser.call(this, parentId, arc1, arc2, arc3, arc4);
    this.name = "Heavy Laser";
    this.structure = 8;
    this.armour = 2;
    this.damage = 100;
    this.optRange = 800;
    this.dmgDecay = 5;
    this.accDecay = 50;
    this.shots = 1;
    this.reload = 2;
    this.beamColorA = "#EA0000";
    this.beamColorB = "orange";
    this.beamWidth = 3;
    this.rakeTime = 70;
}
HeavyLaser.prototype = Object.create(BaseLaser.prototype);

function MediumLaser(parentId, arc1, arc2, arc3, arc4){
    BaseLaser.call(this, parentId, arc1, arc2, arc3, arc4);
    this.name = "Medium Laser";
    this.structure = 8;
    this.armour = 2;
    this.damage = 100;
    this.optRange = 450;
    this.dmgDecay = 10;
    this.accDecay = 70;
    this.shots = 1;
    this.reload = 2;
    this.beamWidth = 2;
    this.rakeTime = 50;
}
MediumLaser.prototype = Object.create(BaseLaser.prototype);
BaseLaser
类还有一些功能

我需要客户端和服务器上HeavyLaser和MediuMLaser的所有通用属性

我的印象是我应该重新创建这些(重的和中等的),而不是在JS上有适当的类,用PHP做它们,然后作为通用JSON对象作为一种“模板”传输到客户端。 在这里,我可以使用JSON字符串从中创建“自定义”对象

这是正确的方法吗?或者,我认为经常发生的这个问题是如何最好地解决的


谢谢

这里最好的共享方式是JSON,因为JSON和PHP都可以理解,但它可以以不同的方式使用

这里可能的解决方案至少有2个:

  • 将默认值存储在JSON中,并从这些文件在后端加载每个模型的默认值,以便使用这些文件在前端实例化您的对象。有点像配置方法
  • 或者通过AJAX请求默认值。因此,您可以避免使用单独的JSON文件,在后端以更自然的方式设置默认值,并在不增加任何开销的情况下传输/更改/使用它

  • 为什么你需要同样的课程?我从来没有听说过在层之间使用1:1类映射的体系结构。嗯,除了传输对象之外,这些对象是哑的(不是贬义的)并且用于数据传输。我不是专业人士。我在做一个基于浏览器的游戏。如您所见,这些类包含关于武器系统的各种信息,这些信息需要显示在用户GUI中。在解析玩家操作(数学)时,服务器上也会使用相同的值。所以我相信我需要两端的“系统”和更多。那么,你不需要相同的类,你需要相同的数据。您可以将其表示为相同的类,但这会导致应用程序紧密耦合。更好的做法是确实有“两次”的类,只是我认为您不需要为每个类都编写那么多代码——您应该能够使用继承、组合和其他方法来定义几个“基类”并从中派生。不管怎样,他们似乎不会做那么多。