im trying to learn how to use javascript objects, and got some issue here.
var playerImg = new Image();
playerImg.src = 'player_stay.png';
var player = {
posX: 50,
posY: 50,
draw: function(){
ctx.drawImage(playerImg, player.posX, player.posY);
}
}
It is posible to insert playerImg into player object ?
Something like player.img
EDIT:
I can make it this way
var player = {
posX: 50,
posY: 50,
draw: function(){
playerImg = new Image();
playerImg.src = 'player_stay.png';
ctx.drawImage(playerImg, player.posX, player.posY);
}
}
But i think it will create new Image(); all the time when i use player.draw();
So im asking if there is a better way to do this and have all parametrs inside a player object ?
If I understand correctly you don’t want to build the
playerImgobject outside/before of theplayerone.Well this is one way you could do it, but I wouldn’t recommend it because it’s not so readable:
This construct
(function(){})();is called a self-executing/self-invoked anonymous function, or an Immediately-Invoked Function ExpressionBTW: this expression is executed only once, when the player object is constructed, so you don’t have to worry about repeatedly creating the Image.