I’m trying to do more OOP in Javascript.
One thing i can’t figure out is how can i modify a variable inside an object from another function?
Here’s how I tried to do it:
function Ball(){
radius = 5;
Y = 20;
X = 25; // The value i would like to change.
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
}
function draw(){
Player();
Ball();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
Ball.X++; // This is where i want to modify the value.
}
So far I’ve only been able to do it if I define X as a global variable, but I dont want to do that since there are other X and Y values.
So how would i access the variable from outside the function?
EDIT:
The solution provided by “nnnnnn” worked to an extent, it changes the X value but I ran into another problem.
My clearRect doesnt clear the animation, so instead of a ball it draws a line that just grows.
This is what the code looks like right now:
function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function() {
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
var ball = new Ball();
function draw(){
Player();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
ball.X++;
}
I have tried moving it around, placing it both in the draw() and ball.draw() functions, but still getting the same result, I also tried doing a fillRect instead of clear but it didnt help.
Anyone able to see whats wrong?
“So far I’ve only been able to do it if I define X as a global variable”
Actually your variables
radius,XandYvariables are all global variables. For them to be properties of an object they need to be set as follows:They’re not local variables within the
Ball()function because they’re not declared withvar– any variables that you assign a value to without declaring them withvarautomatically become global.Your
Ball()function is not creating an object when you call it – in order for it to do so you need to usenew:If you call it with
newthen JS automatically creates a new instance ofBalland within the functionthisrefers to that new instance. So the function should say:Then you can access and change properties as follows:
However that doesn’t really fit with the way you’ve structured your code because you’re trying to call
Ball()to make it draw itself. You probably want something more like this: