【发布时间】:2019-07-16 08:00:33
【问题描述】:
我有一个问题,经过多次尝试解决后无法理解。
为了帮助您理解,这里有 2 个类(游戏和棋盘),以及带有 jQuery 按键控件的第三个文件。游戏关乎游戏逻辑,板关展示。
这是我希望足以理解的部分代码。
// GAME CLASS
function Game(width, height) {
this.width = width;
this.height = height;
this.forbiddenPosition = [];
this.chartBoard = this.resetBoard();
this.generateGame();
}
Game.prototype.generateGame = function () {
this.player1 = new Player("Joueur 1", 100, dagger);
this.player2 = new Player("Joueur 2", 100, dagger);
const playerArray = [this.player1, this.player2];
}
Game.prototype.getPlayer1 = function () {
return this.player1;
};
Game.prototype.getPlayer2 = function () {
return this.player2;
};
Game.prototype.switchTurn = function (player1, player2) {
console.log(player1);
console.log(player2);
};
// BOARD CLASS
const ctx = $('#board').get(0).getContext('2d');
function Board (width, height) {
this.width = width;
this.height = height;
this.game = new Game(this.width, this.height);
this.displayInfoPlayers(this.game.getPlayer1(), this.game.getPlayer2());
}
Board.prototype.displayInfoPlayers = function (player1, player2) {
$('.canvas-side__left').css('visibility', 'visible');
$('.canvas-side__right').css('visibility', 'visible');
$('.canvas-side__left').addClass('animated slideInLeft');
$('.canvas-side__right').addClass('animated slideInRight');
$(".canvas-side__left").html("<h2 class='canvas-side--title'>" + player1.name + "</h2><p class='canvas-side--health'>" + player1.health + "</p><p class='canvas-side--health'>" + player1.weapon.name + "</p>");
$(".canvas-side__right").html("<h2 class='canvas-side--title'>" + player2.name + "</h2><p class='canvas-side--health'>" + player2.health + "</p><p class='canvas-side--health'>" + player2.weapon.name + "</p>");
};
// CONTROL
$(document).on('keypress', function (e) {
if (e.which == 13) {
Game.prototype.switchTurn(Game.prototype.getPlayer1(), Game.prototype.getPlayer2());
e.stopPropagation();
}
});
Board 类链接到 Game 类,因此使用它。使用 jQuery 代码的控件在第三个文件中,而不是在一个类中。
当我按 Enter 键时,player1 和 2 未定义。我尝试了不同的方法来调用 getter 函数,但没有任何效果。我还尝试将控件放入游戏文件中,但仍然没有。
我得到 undefined 或 getPlayer1() 不是函数。
我正在寻找一种从任何地方调用这些 getter 函数的方法,以便我可以使用我需要在板上移动的 player1 和 2。
【问题讨论】:
-
Game.prototype.getPlayer1()将返回undefined,因为this指的是Game.prototype而不是Game的实例。您需要使用const game = new Game()等新运算符创建Game的实例,然后运行game.getPlayer1()等 -
@adiga 但是函数返回this.player1。这就是为什么我不明白这个问题。
-
正如我在上一条评论中提到的,当您调用
Game.prototype.getPlayer1()时,this指的是Game.prototype。Game.prototype内部没有player1属性。它只存在于使用new operator 创建的Game对象上。应该是:const game = new Game(); game.getPlayer1() -
@adiga 谢谢。
标签: javascript jquery oop object