Let's start a journey into the world of programming with a fun analogy. Imagine you're at a bustling...
Let's start a journey into the world of programming with a fun analogy. Imagine you're at a bustling train station. There are different types of trains, each with its unique features and functions. This is quite similar to how OOP in JavaScript works.
Object-Oriented Programming (OOP) is like a train system. Just like a train is made up of different coaches, an application in OOP is composed of different objects. These objects are instances of classes, which can be considered as the blueprint for creating objects.
In JavaScript, objects are like special trains. They carry values in properties and can perform tasks with methods.
For example, let's take a train
object:
let train = {
name: 'Express',
speed: 100,
capacity: 500,
start: function() {
console.log(this.name + ' has started moving');
},
stop: function() {
console.log(this.name + ' has stopped');
}
};
Here
, name
, speed
, and capacity are properties of the train, and start()
and stop()
are the methods.
The Blueprint: Classes
Classes are like blueprints used to create trains. Just like each train follows a blueprint to have an engine, bogies, and certain speed, each object in JavaScript follows a class.
Here's an example of a Train
class in JavaScript:
class Train {
constructor(name, speed, capacity) {
this.name = name;
this.speed = speed;
this.capacity = capacity;
}
start() {
console.log(`${this.name} has started moving`);
}
stop() {
console.log(`${this.name} has stopped`);
}
}
To create a new train, we can now use:
let expressTrain = new Train('Express', 100, 500);
And just like a real train, our expressTrain
can now start and stop:
expressTrain.start();
expressTrain.stop();
The Special Trains: Inheritance
Let's say we now want to add a special type of train, a "Bullet Train", which has all the properties of a train, but can also tilt. We can achieve this through inheritance.
In JavaScript, we use the keyword extends
to inherit from another class. Here's how we can create a BulletTrain
class that extends the Train
class:
class BulletTrain extends Train {
constructor(name, speed, capacity) {
super(name, speed, capacity);
}
tilt() {
console.log(`${this.name} is tilting`);
}
}
Now, we can create a BulletTrain
that can do everything a normal Train
can do, and also tilt:
let bulletTrain = new BulletTrain('Shinkansen', 200, 400);
bulletTrain.start();
bulletTrain.stop();
bulletTrain.tilt();
And there you go! That's a simple and friendly introduction to Object-Oriented Programming in JavaScript, seen through the lens of a bustling train station. Just remember, objects are the special trains, classes are the blueprints for these trains, and inheritance lets us create new types of special trains. Choo Choo! Happy coding!