JavaScript OOP Example

The following is an example of a JavaScript program that demonstrates object-oriented programming (OOP) concepts:

In this example, a constructor function called "Car" is defined, which takes in two parameters, "make" and "model". These parameters are used to set the make and model properties of the Car object. Additionally, the speed property is set to 0 when the Car object is created.

Next, three prototype methods called "accelerate", "brake" and "currentSpeed" are defined on the Car object using the "prototype" property. The accelerate method increments the speed property of the Car object by the specified amount, the brake method decrements the speed property of the Car object by the specified amount and the currentSpeed method outputs the current speed of the Car object to the console.

A new Car object is created using the "new" keyword and the constructor function, with "Toyota" and "Camry" passed as the make and model parameters, respectively.

Finally, the accelerate and brake methods are called on the car1 object and the currentSpeed method is called to output the current speed of the car1 object to the console.

You can implement this program in any JavaScript development environment that supports the use of OOP concepts, such as a text editor with a browser or Node.js.

No comments:

Post a Comment

Please disable your ad blocker to support this website.

Our website relies on revenue from ads to keep providing free content.