ich auf dem Canvas-Element war das Surfen mit JavaScript-Spiele zu verwenden und fand ich diesen Code:JavaScript-Konstruktor: Ist das eine Eigenschaft oder eine Variable?
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);
}
Meine Frage ist, was ctx
ist eine Eigenschaft? Oder eine private Variable?
ctx
ist nicht deklariert oder sogar außerhalb dieses Konstruktors verwendet (wie: var ctx
). Es ist nur innerhalb dieses Codes.
Ich höre, wenn Sie eine Variable mit einem Wert direkt ohne das reservierte Wort var
setzen, deklarieren Sie eine globale. Aber diese ctx
Variable wird nicht außerhalb dieses Konstruktors verwendet, ist also nutzlos?
Auch sie tun dasselbe, wenn sie die Eigenschaft key
auf eine Instanz eines Objekts setzen.
Der ganz 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);
}
tatsächlich ist es eine globale Variable. – epascarello
Ja, sieht wie schlechter Code aus. Es sollte höchstwahrscheinlich "var ctx" sein. –
Es ist eine Variable, aber es könnte außerhalb dieser Funktion deklariert werden, also ist es nicht unbedingt global. –