我很困惑如何定义和调用JavaScript对象方法。我试图用JavaScript创建游戏,并希望创建具有控制每个元素的函数的对象。目前,game.update
函数在尝试调用player.update
时调用错误。它找不到方法。我该如何定义和调用方法。我来自使用java。
//INIT
var game;
var paper;
var key = [0, 0, 0, 0, 0]; // left, right, up, down
window.onload = function () {
paper = Raphael("canvas", 640, 480);
game = new Game();
game.init();
};
//GAME
function Game() {
this.player = new Player();
this.score = 0;
this.drawCanvas = function () {
paper.clear();
paper.rect(0, 0, 640, 480, 10).attr({
fill: "#fff",
stroke: "none"
});
paper.text(40, 10, "Score " + this.score);
paper.ellipse(this.player.positionX, this.player.positionY, 10, 10);
}
this.update = function () {
this.player.update.call();
this.drawCanvas.call()();
}
this.init = function () {
this.drawCanvas();
setInterval(this.update, 35);
}
}
//UNITS
//PLAYER
function Player() {
this.positionX = 100;
this.positionY = 100;
this.update = function () {
if (key[0]) { //left
this.positionX -= 3;
game.score += 3;
}
if (key[1]) { //right
this.positionX += 3;
game.score += 3;
}
if (key[2]) { //up
this.positionY -= 3;
game.score += 3;
}
if (key[3]) { //down
this.positionY += 3;
game.score += 3;
}
if (key[4]) { //space
}
if (this.positionX > 640) {
this.positionX = 640;
} else if (this.positionX < 0) {
this.positionX = 0;
} else if (this.positionY > 480) {
this.positionY = 480;
} else if (this.positionY < 0) {
this.positionY = 0;
}
}
}
function changeKey(which, to) {
switch (which) {
case 65:
case 37:
key[0] = to;
break; // left
case 87:
case 38:
key[2] = to;
break; // up
case 68:
case 39:
key[1] = to;
break; // right
case 83:
case 40:
key[3] = to;
break; // down
case 32:
key[4] = to;
break; // space bar;
case 17:
key[5] = to;
break; // ctrl
}
}
document.onkeydown = function (e) {
changeKey((e || window.event).keyCode, 1);
};
document.onkeyup = function (e) {
changeKey((e || window.event).keyCode, 0);
};
我收到以下错误:
Uncaught TypeError: Cannot read property 'update' of undefined main.js:25
答案 0 :(得分:3)
这是无效的语法:
this.update : function(){
你想要这个
this.update = function(){
答案 1 :(得分:2)
问题在于您从update
分离了this
方法。
this.init = function () {
this.drawCanvas();
setInterval(this.update, 35); // <-------- passing `update` without `this`
}
所以当你到update()
this.player.update.call();
this
的值是全局对象,没有player
属性,因此您尝试访问.update.call()
上的undefined
。
你需要保持它们的约束力:
this.init = function () {
this.drawCanvas();
var self = this;
setInterval(function() {
self.update();
}, 35);
}
或者使用Function.prototype.bind
创建一个新功能,this
永久绑定到该功能。
this.init = function () {
this.drawCanvas();
setInterval(this.update.bind(this), 35);
}