[JavaScript] Object-Oriented Programming (OOP) with JavaScript : Coding CHallenge #1
![[JavaScript] Object-Oriented Programming (OOP) with JavaScript : Coding CHallenge #1](https://cdn.hashnode.com/res/hashnode/image/unsplash/g5jpH62pwes/upload/v1658547825668/t9c2wdxvg.jpeg)
Use a constructor function to implement a 'Car'. A car has a 'make' and a 'speed' property. The 'speed' property is the current speed of the car in km/h.
Implement an 'accelerate' method that will increase the car's speed by 10, and log the new speed to the console.
Implement a 'brake' method that will decrease the car's speed by 5, and log the new speed to the console.
Create 2 'Car' objects and experiment with calling 'accelerate' and 'brake' multiple times on each of them.
Test data:
- Data car 1: 'BMW' going at 120 km/h
- Data car 2: 'Mercedes' going at 95 km/h
const Car = function (make, speed) {
this.make = make;
this.speed = speed;
};
const bmw = new Car('BMW', 120);
const mercedes = new Car('Mercedes', 95);
Car.prototype.acclerate = function () {
this.speed += 10;
console.log(`${this.make} is going to at ${this.speed} km/h`);
};
Car.prototype.brake = function () {
this.speed -= 5;
console.log(`${this.make} is going to at ${this.speed} km/h`);
};
bmw.acclerate();
bmw.acclerate();
bmw.brake();
bmw.acclerate();
mercedes.acclerate();
mercedes.acclerate();
mercedes.brake();
mercedes.acclerate();