Hello… I’ve actually been writing js for years, but I really want to learn OOP. The problem is I’m very much NOT mathematically minded and it’s tough for me to grasp. I’ve been going through ‘Simply JavaScript’ and have noticed that the authors make their functions objects, e.g. var SoccerBall ={ init: function() { stuff…
But then that code isn’t reusable and only fires after the doc is loaded. Also they don’t really explain WHY they do it
their function:
var SoccerBall =
{
init: function()
{
SoccerBall.frameRate = 25;
SoccerBall.deceleration = 10;
SoccerBall.div = document.getElementById("soccerBall");
SoccerBall.targetX = 600;
SoccerBall.targetY = 150;
SoccerBall.originX = parseInt(Core.getComputedStyle(SoccerBall.div, "left"), 10);
SoccerBall.originY = parseInt(Core.getComputedStyle(SoccerBall.div, "top"), 10);
SoccerBall.x = SoccerBall.originX;
SoccerBall.y = SoccerBall.originY;
SoccerBall.animate();
},
animate: function()
{
SoccerBall.x += (SoccerBall.targetX - SoccerBall.x) / SoccerBall.deceleration;
SoccerBall.y += (SoccerBall.targetY - SoccerBall.y) / SoccerBall.deceleration;
if ((SoccerBall.targetX > SoccerBall.originX && Math.round(SoccerBall.x) >= SoccerBall.targetX) || (SoccerBall.targetX < SoccerBall.originX && Math.round(SoccerBall.x) <= SoccerBall.targetX))
{
SoccerBall.x = SoccerBall.targetX;
SoccerBall.y = SoccerBall.targetY;
}
else
{
setTimeout(SoccerBall.animate, 1000 / SoccerBall.frameRate)
}
SoccerBall.div.style.left = Math.round(SoccerBall.x) + "px";
SoccerBall.div.style.top = Math.round(SoccerBall.y) + "px";
}
};
Core.start(SoccerBall);
I’m attempting to make a reusable animate object out of this:
function Mover (movDiv, divLoco) {
this.frameRate = 60;
this.deceleration = 10;
this.div = document.getElementById(movDiv);
this.targetY = divLoco;
this.originY = parseInt(Core.getComputedStyle(this.div, "top"), 10);
this.y = this.originY;
};
Mover.prototype.animate=function(){
this.y += (this.targetY - this.y) / this.deceleration;
if ((this.targetY > this.originY && Math.round(this.y) >= this.targetY) || (this.targetY < this.originY && Math.round(this.y) <= this.targetY))
{
this.y = this.targetY;
}
else
{
setTimeout(Mover.prototype.animate, 1000 / this.frameRate);
}
this.div.style.top = Math.round(this.y) + "px";
}
Right now I’m calling the function like (just to test the function):
var Mover1=new Mover('reco01', -400);
Mover1.animate();
And it works at first - the div moves one step - then the variables lose all their values, and the timeout counter just runs on.
I’m doing this mostly as an exercise on how to do it. I know jquery makes this easy, but I want to understand this and hopefully begin to understand OOP with javascript. I haven’t found a good tutorial on this kind of thing that has good visual examples. A lot of them use math/calculator functionality and numbers make my eyes cross.
Any insight is appreciated!