Object Orienting Programming Basics :: part 3 :: Combining properties and methods
In my previous posts, I've introduced properties and methods. Let's see how we could combine them to provide useful functionality for our Animal class.
I will add two new properties to the Animal class.
class Animal {
speed;
distance;
[...]
}
How distance and speed are related? In physics, we learn that if the speed is constant then the step dx = v dt, where v is speed (velocity). This means that in each cycle (period) that the object moves by one step, distance traveled (dx) is increased by v dt. Assuming that dt = 1, which means that distance moved in one unit of time is increasing by v.
This a physics-compliant version of the move() method:
move() {
var dt = 1;
var dx = this.speed * dt;
this.distance += dx;
}
But in a programming tutorial, you should always have KISS principle in mind, so the above method could simplified in one line:
move() {
this.distance += this.speed;
}
Every time the animal moves, the distance is increasing by the speed factor. If the animal is fast (eg. the speed is high), the more distance is covered. If the speed is low, less distance is covered.
Notice this keyword used before speed and distance, inside the move method.
Let's see the whole example:
class Animal {
speed;
distance;
move() {
this.distance += this.speed;
}
}
Let's create two instances of the Amimal class.
rabbit = new Animal();
rabbit.distance = 0;
rabbit.speed = 100;
rabbit.move();
console.log(`rabbit distance is ${rabbit.distance}`);
turtle = new Animal();
turtle.distance = 0;
turtle.speed = 10;
turtle.move();
console.log(`turtle distance is ${turtle.distance}`);