简单的JavaScript游戏:由于构造函数或条件运算符导致的对象创建错误

时间:2013-06-18 08:15:09

标签: javascript object constructor conditional-statements

我对java很新,我一直在慢慢建立一个游戏。我知道有不同的方法来编写对象,但在推荐之后,我就像这个模型一样构建它们:

function object(x,y,z){
    var object={
    a:x,
    b:y,
    c:z
    };
    function doSomething(){
        ...
    }
    return object;
}

一切都很顺利,直到我让我的“球员”射门。螺栓是对象,每个新创建的螺栓都存储在一个数组中。这是:

var playerBolts=new Array();

这是在拍摄时在“玩家”对象内部调用的方法:

function shootBolt(){
    playerBolts.push(bolt(player.playerNum,player.facingLeft,player.x,player.y));
}

从玩家的当前位置开始射击,根据他所朝向的方向,螺栓将朝那个方向移动。为了让螺栓知道它必须经过哪一个,我在我的bolt的对象构造函数中有一个名为“facing”的布尔值(上面的player.facingLeft)。当我在三元运算符中使用该布尔值来提供方向速度时,它总是给我一个错误:“ReferenceError:facingLeft未定义”。

这是创建的螺栓对象:

function bolt(fromPlayer,facing,playerX,playerY){
    var bolt={
        playerNum:fromPlayer,
        damage:10,
        facingLeft:facing, //The direction at which the bolt moves, if left, true
        x:playerX, //The x position of the bolt
        y:playerY, //The y position of the bolt
        xSpeed:facingLeft ? -3 : 3, //The horizontal speed at which the bolt is moving
        ySpeed:0, //The vertical speed at which the bolt is moving
        W:3, //The width of the bolt's model
        H:3, //The height of the bolt's model
        color:"red", //The color of the bolt's model
        update:update,
        draw:draw
    };
    function update(){ 
        ...
    }       
    function draw(){
        ...
    }
    return bolt;
}

如果我删除三元运算符并将xSpeed设置为预定义值,则构造函数中的所有其他变量似乎都很好。所以我真的很想知道我在这里做错了什么...我尝试了一个if / else语句,但我得到:“SyntaxError:missing:after property id”。

我是否必须将所有物品更改为其他型号,或者是否有某些我没有看到的物体?如果不清楚,我可以随时提供更多信息或代码。

谢谢?! :P

2 个答案:

答案 0 :(得分:1)

facingLeft ? -3 : 3替换为facing ? -3 : 3,因为您无法引用尚未创建的对象的属性(即“facingLeft”)。

另请参阅此 short demo

答案 1 :(得分:1)

1)你在构建时不能引用它。如果在计算属性值时使用“this”,则将使用当前上下文,而不是新对象:

function someFunc() {
    var functionThis = this;

     var aNewObject = {
                        a : 3,
                        b : this.a *2   // nAn : this.a == functionThis.a                                           
                        }

     // this will be working :
     aNewObject.b = aNewObject.a * 2;
   }

所以当你引用'this.face'时,它会给出:undefined,所以三元运算符 总会切换到假的情况。

在您的情况下,解决方案很简单:使用faces参数而不是尝试获取facingLeft对象属性:

    xSpeed:facing ? -3 : 3,

2)如果您使用了很多螺栓,请考虑在原型上设置方法,以便更快地创建并减少垃圾创建。