Javascript is an Object-Oriented scripting language.
Object-Oriented Programming refers to the idea of making objects for the real world things while programming. Just like any other object-oriented programming language, one can create classes and objects of the classes in javascript.
How to create a javascript class?
Javascript class is created using the keyword class as shown in the below image.
Syntax to create Javascript Class |
How to create a javascript constructor?
Javascript constructor can be created using the constructor keyword. The syntax is shown in the below image
Syntax of javascript constructor |
Let's create a calculator using javascript class and constructor
Before beginning with the code, it is necessary to list the elements and functionalities. Here, we are going to make a calculator like the below image.
Calculator |
List of functions
- To set the display value when the user clicks on any button. If the user clicks on 1 then the display value should be 1. If the user clicks + then this should be appended to the display screen (textbox) and so on.
- Whenever user clicks on "=", the calculated value should be displayed on the textbox
- To clear the textbox when the user clicks on button C.
So, to implement this we will create a class Calculator and there will be 3 methods inside the class for each of the functionality mentioned above.
HTML Code for the calculator
Html Code for the calculator |
CSS Code for the calculator
CSS code for the calculator |
Javascript Code for the calculator
For the calculator, we will create a class called Calculator having properties Expression and displayElement. We will create a constructor that will set the properties of the Calculator class during initialization. There will be 3 methods inside this class to set the values, evaluate values and to clear the values as shown in the below image
Calculator Class, Constructor, and Methods |
The eval() method is used to evaluate any string expression like "1-2", "10+20", etc in javascript
The Button Click Event
Whenever we click on any of the buttons, all we want to do is to append that value to the textbox. For that, we have to add an event listener for all the buttons as shown below:
Button Click Event |
The same thing needs to be followed for Evaluate and clear button click events. A calculator object needs to be created with the property values and then call the respective methods as shown in the below image:
Evaluate and Clear Button Click Event |
You can check this example on jsFiddle. For any queries, you can reach out at [email protected]. To get notified for the releases, subscribe through email.