Classes, Drawio Diagram on classes
methods, instantiating objects, using objects, calling methods, parameters, return values
Classes:
What is a class, and what is it used for? A class is a blueprint or template for creating objects. It defines attributes (data) and methods (actions) that the objects created from the class will have.
Methods:
Methods are functions that are defined inside a class. They describe actions an object of that class can perform. For example, a class Car might have a method start_engine() to start the car’s engine.
Example: (from code)
startWalking() {
this.stopAnimate();
this.animate(this.obj["Walk"], 3);
}
startRunning() {
this.stopAnimate();
this.animate(this.obj["Run1"], 6);
}
startPuffing() {
this.stopAnimate();
this.animate(this.obj["Puff"], 0);
}
startCheering() {
this.stopAnimate();
this.animate(this.obj["Cheer"], 0);
}
Instantiating Objects:
Instantiating Objects are creating an instance (or object) of a class. When you instantiate a class, you create a unique object with its own data and behavior. For example, creating a Car object named my_car from the Car class.
Example: (from code)
- Mario is a class
- mario_metadata (a dictionary of animation data) is passed as an argument to the Mario constructor.
- const mario creates an instance (object) of the Mario class.
const mario = new Mario(mario_metadata);
Using Objects:
After creating an object, you can use it by interacting with its attributes (data) or calling its methods (actions). For example, after instantiating a Car object, you can call its start_engine() method or check its color attribute.
Example: (from code)
this.marioElement.style.position = "absolute";
Calling Methods:
To use the actions defined in a class, you call the object’s methods. Methods might need parameters to specify how they should behave, like providing a speed value to a drive() method. Calling a method might return a result.
Example: (from code)
window.addEventListener("touchstart", (event) => {
event.preventDefault(); // prevent default browser action
if (event.touches[0].clientX > window.innerWidth / 2) {
// move right
if (currentSpeed === 0) { // if at rest, go to walking
mario.startWalking();
} else if (currentSpeed === 3) { // if walking, go to running
mario.startRunning();
}
} else {
// move left
mario.startPuffing();
}
});
Parameters:
Values passed into methods when you call them. They allow the method to work with different inputs. For example, a drive(speed) method might take the speed as a parameter to decide how fast the car should go.
Example: (from code)
animate(obj, speed) {
let frame = 0;
const row = obj.row * this.pixels;
this.currentSpeed = speed;
}
Return Values:
The output that a method gives after performing an action. When a method completes, it can return a result to be used later. For example, a method that calculates the area of a circle might return that value so you can use it elsewhere in your program.