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

Unable to call object properties from functions in JavaScript

本文关键字:函数调用 对象 属性 JavaScript      更新时间:2023-09-26

我是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);
};

但它不起作用!控制台显示"无法获取未定义或null引用的属性'x'"。我是否在语法上犯了任何错误,或者这样做是不可能的?

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

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

简单修复:

真的没有理由打电话给

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();

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

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