无法从JavaScript中的函数调用对象属性

时间:2016-05-11 05:54:18

标签: javascript function object

我是JavaScript的新手,想要为练习创建一个简单的乒乓游戏。 我可以轻松地在画布上绘制游戏区域,但现在我尝试绘制球棒时会出现问题。

我创建了一个带有一些属性的playerBat对象。

var playerBat = {
    batWidth:20, 
    batHeight:100, 
    x:10, 
    y:(height/2)-(batHeight/2), 
    spdY:10
};

然后在函数" drawPlayerBat"我只是画了一个带有这些属性作为参数的矩形。

function drawPlayerBat() {
    ctx.fillStyle = "white";
    ctx.fillRect(playerBat.x, playerBat.y, playerBat.x+playerBat.batWidth, playerBat.y+playerBat.batHeight);
};

但它不起作用!控制台说"无法获得财产' x'未定义或空引用"。我在语法上犯了什么错误,或者这样做是不可能的吗?

以下是整个代码...... http://codepen.io/anon/pen/YqgVog?editors=1010

任何帮助将不胜感激。 感谢。

2 个答案:

答案 0 :(得分:0)

您需要删除batHeight。就像下面这样。

 var playerBat = {
        batWidth:20, 
        batHeight:100, 
        x:10, 
        y:(height/2)-(100/2), 
        spdY:10
    };

答案 1 :(得分:0)

轻松修复:

没有理由打电话

y:(height/2)-(batHeight/2),

因为你在batHeight上面定义了两行。它不会动态表现 - 一旦你设置它就会在batHeight更改时不会发生变化,它会保持不变。

了解batHeight值,您可以简单地说

y:(height/2)-(50),

你可能想要什么答案:

如果问题是关于JavaScript中的自引用,那么答案就是在对象内部设置函数内部的值并在声明它之后对其进行初始化。例如:

var playerBat = {
    batWidth: 20, 
    batHeight: 100, 
    x: 10, 
    spdY:10,
    init: function(){
        this.y = (height/2)-(this.batHeight/2);
        return this;
    }
}.init();