简体   繁体   中英

Calling function bad argument

I'm trying to write a game and I got a problem with function showing player:

function Furry() {
  this.board=document.querySelectorAll('#board div');
  this.x = 0;
  this.y = 0;
  this.direction = "right";
}

and:

showFurry=function(){
  this.x = Math.floor(Math.random() * 10);
  this.y = Math.floor(Math.random() * 10);
  this.board[ this.position(this.furry.x , this.furry.y) ].classList.add('furry');
}

and in consol when I want to call function I got this:

Uncaught TypeError: Cannot read property 'x' of undefined

https://jsfiddle.net/mdx3w24c/

At this state after calling function showFurry and showCoin I should receive this: 在此处输入图片说明

Try removing the functions showFurry and showCoin . Then, make a function in the Game class that will do those things.

Game.prototype.start = function() {
    this.board[this.position(this.coin.x, this.coin.y)].classList.add('coin');
    this.board[this.position(this.furry.x, this.furry.y)].classList.add('furry');
};

Then when you start your game, instead of calling showFurry and showCoin you can call Game.start() ;

var game = new Game();
game.start();

Also your Coin constructor set random values to x & y, but the furry construct set them both to 0, then set them to random values in the showFurry function. In this fiddle, I've moved that to the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM