Javascript函数无法获取'this'变量

时间:2012-10-22 02:58:16

标签: javascript html5 variables

我正在开始一个小型HTML5游戏,这是我正在做的第一个。目前,我正在创建一个包含变量的函数,我真的不知道它叫什么,我只记得如何从教程中做到这一点。无论如何,我正在尝试使用'this'设置一些变量但它似乎没有得到一个值。这是我认为导致问题的代码:

function ship() {
    this.width = 100;
    this.height = 75;
    this.drawX = gameWidth/2 - this.width/2;
    this.drawY = gameHeight + this.height;
}
然而,

this.drawX和Y似乎没有得到价值。另外,我确定gameHeight和gameWidth有一个值。

编辑:这是绘图功能和其余代码:

var player = new ship();

var gameWidth  = canvasShip.width;
var gameHeight = canvasShip.height;

var sprites = new Image();
sprites.src = 'images/spriteSheet.png';

var canvasPlayer = document.getElementById('canvasShip');
var ctxPlayer = canvasPlayer.getContext('2d');

//Clear any canvas
function clearCtx(canvas) { 
    canvas.clearRect(0,0,gameWidth,gameHeight);
}

//Ship object, the player
function ship() {
    this.width = 100;
    this.height = 75;
    console.log(gameWidth,gameHeight);
    this.drawX = gameWidth/2 - this.width/2;
    this.drawY = gameHeight + this.height;
}

ship.prototype.draw = function() {
    clearCtx(ctxPlayer);
    ctxPlayer.drawImage(sprites,0,0,this.width,this.height,this.drawX,this.drawY, this.width, this.height);
}

1 个答案:

答案 0 :(得分:2)

您的代码中的这部分看起来很可疑:

var player = new ship();

var gameWidth  = canvasShip.width;
var gameHeight = canvasShip.height;

ship()的构造函数中,gameWidthgameHeight的值为undefined

撤销声明应按预期工作:

var gameWidth  = canvasShip.width,
gameHeight = canvasShip.height,
player = new ship();

这是JavaScript查看代码的方式:

var gameWidth, gameHeight, player, ship;

ship = function() { ... }

player = new ship();
gameWidth = 123;
gameHeight = 456;

ship()的声明在一个有时被称为“hoisting”的过程中向上移动,使其更明显地表现为这样做。