This is an exercise to construct a basic calculator in JavaScript using the principles of object-oriented programming (OOP).
The calculator implements the Model View Controller design pattern (MVC). The core functionality and the UI rendering are completely separated in the code.
For an example implementation of this calculator, see OOP Basic Calculator on JSFiddle.
I coded this project as part of a Follow the Pattern course.
To create your calculator, follow these steps:
- Create a copy of the file
source/main.js
, and open it with your text editor. - At the bottom of the file, delete the example.
- Create a
CalculatorCore
object with no parameters. - Create a
CalculatorUIOptions
object. The first parameter is the CSS selector of the HTML element where you want to insert the calculator into the DOM. Optionally, specify the colors of the calculator with the following parameters:- Specify a CSS color value in the second parameter to determine the color of the calculator's background.
- Specify a CSS color value in the third parameter to determine the color of the buttons.
- Specify a CSS color value in the fourth parameter to determine the color of the calculator's display.
- Specify a CSS color value in the fifth parameter to determine the color of the text in the calculator.
- Create a
CalculatorUI
object with two parameters. The first parameter is theCalculatorCore
object, and the second parameter is theCalculatorUIOptions
object you have created in the previous steps. - Call the
render
method of theCalculatorUI
object with no parameters.
As a result, you have created your calculator.