To convert the provided script into a class-based approach, you can encapsulate the functionality within a class. This provides a structured and organized way to manage the state and operations of your script. Here’s how you could refactor the given script into a class:
class Calculator {
constructor(containerId, screenId) {
this.container = document.getElementById(containerId);
this.screen = document.getElementById(screenId);
this.init();
}
handleClick = (event) => {
const key = event.target.textContent;
switch (key) {
case 'C':
this.screen.textContent = '0';
break;
case '=':
try {
const result = Function('return ' + this.screen.textContent)();
this.screen.textContent = result;
} catch (e) {
this.screen.textContent = 'Błąd'; // Error in Polish
}
break;
default:
if (this.screen.textContent.length > 8) {
return;
}
if (this.screen.textContent === '0') this.screen.textContent = key;
else this.screen.textContent += key;
break;
}
}
init = () => {
// Using event delegation instead of adding an event listener to each child
this.container.addEventListener('click', this.handleClick);
}
}
// Using the DOMContentLoaded event to ensure the DOM is fully loaded before initializing
document.addEventListener('DOMContentLoaded', () => {
new Calculator('container', 'screen');
});
Key Changes and Improvements:
-
Encapsulation: The functionality related to the calculator is now encapsulated within the Calculator class, making it easier to manage and reuse.
-
Initialization through Constructor: The constructor initializes the calculator by binding it to specific container and screen elements in the DOM and then running the init method.
-
Event Delegation: Instead of adding an event listener to each child of the container, this version adds a single event listener to the container itself (event delegation). This improves performance, especially if there are many buttons.
-
Arrow Functions: Arrow functions are used for methods that need access to the class instance’s this context, particularly in event handlers.
-
Typo Correction: Corrected the typo lenght to length in the checking of the screen text content's length.
This approach follows best practices in modern JavaScript and enhances the scalability, readability, and maintainability of your code.