Reputation: 55
i always get the error that player.draw() is not a function but i can't find the problem. The Player class exists, but not the draw method :( Wish i could give you more details, but there are not more. Thanks for your help, here is the code:
var version = "0.0.1";
var is_playing = false;
init();
function init(){
background_canvas = document.getElementById("background-canvas");
background_ctx = background_canvas.getContext("2d");
main_canvas = document.getElementById("main-canvas");
main_ctx = main_canvas.getContext("2d");
requestaframe = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60); };
})();
player = new Player();
start_loop();
}
function mouse(e){
var x = e.pageX - document.getElementById("game-holder").offsetLeft;
var y = e.pageY - document.getElementById("game-holder").offsetTop;
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
}
function Player(){
this.color = "yellow";
}
Player.prototype.draw = function(){
main_ctx.fillStyle = this.color;
main_ctx.arc(205, 70, 25, 0, 2*Math.PI);
main_ctx.fill();
};
function clearStage(){
main_ctx.clearRect(0, 0, 800, 600);
}
function start_loop(){ is_playing = true; loop(); }
function stop_loop(){ is_playing = false; }
function loop(){
clearStage();
main_ctx.fillStyle = "blue";
main_ctx.fillRect(175, 100, 450, 450);
player.draw();
if(is_playing) requestaframe(loop);
}
Upvotes: 0
Views: 118
Reputation: 74036
You try to use hoisting, but do not seem to have understood it completely.
In general hoisting moves functions and variable declarations (not assignments!) to the top of the current scope. That's the reason, why you can call your init()
method, before you actually declare it.
So stripping your code down a little, it looks like this
init();
function init() { ... }
function Player() { ... }
Player.prototype.draw = ...;
After hoisting (so the way your code is evaluated) it looks like this:
function init() { ... }
function Player() { ... }
init();
Player.prototype.draw = ...;
So you can clearly see, when you first call init()
the draw()
method has not been attached to the Player
prototype, hence it is undefined.
Simple solution is to change the order of your code and move the init()
call to the bottom.
Upvotes: 1
Reputation: 147363
Function declarations are processed before code execution begins, so you can call init before its declaration:
init();
function init(){...}
Assignments happen later, during code execution, so the assignment:
Player.prototype.draw = function(){...}
hasn't occurred when you call init and hence Player.prototype.draw is undefined when you call init.
Move the call to the bottom of the script, or at least below all assignments to Player.prototype.
Upvotes: 0