I was surfing on the canvas element, to use with JavaScript games and I found this code:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = myGameArea.context; // **why not: var ctx= myGameArea.context ???**
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
My question is what is ctx
a property? Or a private variable?
ctx
is not declared or even used, outside of this constructor (like: var ctx
). It is only inside this code.
I hear if you set a variable with a value directly without the var
reserved word, you are declaring a global. But that ctx
variable is not being used outside that constructor, so is useless?
Also they do the same thing when setting the key
property to an instance of an object.
The entirely code...
var myGamePiece;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 120);
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}