Estoy haciendo una calculadora para un bootcamp de 12 semanas y el MVP establece que no debemos usar constructores.
A continuación se muestran todas las funciones dentro del constructor. Necesito que todas las funciones sigan funcionando, solo que NO las necesito dentro de un constructor para cumplir con los requisitos de mi MVP.
Entiendo conceptualmente cómo hacer una calculadora, y he optado por revisar y reescribir el JS estándar con notas para solidificar mi comprensión.
class Calculator { constructor(previousOperandTextElement, currentOperandTextElement) { this.previousOperandTextElement = previousOperandTextElement this.currentOperandTextElement = currentOperandTextElement this.clear() } clear() { this.currentOperand = '' this.previousOperand = '' this.operation = undefined } delete() { this.currentOperand = this.currentOperand.toString().slice(0, -1) } appendNumber(number) { if (number === '.' && this.currentOperand.includes('.')) return this.currentOperand = this.currentOperand.toString() + number.toString() } chooseOperation(operation) { if (this.currentOperand === '') return if (this.previousOperand !== '') { this.compute() } this.operation = operation this.previousOperand = this.currentOperand this.currentOperand = '' } compute() { let computation const prev = parseFloat(this.previousOperand) const current = parseFloat(this.currentOperand) if (isNaN(prev) || isNaN(current)) return switch (this.operation) { case '+': computation = prev + current break case '-': computation = prev - current break case '*': computation = prev * current break case '÷': computation = prev / current break default: return } this.currentOperand = computation this.operation = undefined this.previousOperand = '' } getDisplayNumber(number) { const stringNumber = number.toString() const integerDigits = parseFloat(stringNumber.split('.')[0]) const decimalDigits = stringNumber.split('.')[1] let integerDisplay if (isNaN(integerDigits)) { integerDisplay = '' } else { integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 }) } if (decimalDigits != null) { return `${integerDisplay}.${decimalDigits}` } else { return integerDisplay } } updateDisplay() { this.currentOperandTextElement.innerText = this.getDisplayNumber(this.currentOperand) if (this.operation != null) { this.previousOperandTextElement.innerText = `${this.getDisplayNumber(this.previousOperand)} ${this.operation}` } else { this.previousOperandTextElement.innerText = '' } } }Primero un comentario: los parámetros del constructor son inútiles, ya que el constructor asigna nuevos valores inmediatamente mediante su llamada a clear .
Sin funciones prototipo (instancia de clase), podría asignar a cada función un parámetro que represente el estado de la calculadora. O bien, si hubiera utilizado esta clase para crear una sola instancia, podría hacer que ese estado sea global, que es lo que podría ser el enfoque sugerido en un curso para principiantes.
En el último caso (globales), defina cada propiedad actual de this como variable global, así:
var previousOperandTextElement = "", currentOperandTextElement = "", operation;Y entonces:
this. del códigofunction antes de cada métodoconstructor justo debajo de las declaraciones var globalesclass y la función constructorAl igual que:
var previousOperandTextElement = "", currentOperandTextElement = "", operation; clear(); function clear() { currentOperand = '' previousOperand = '' operation = undefined } function delete() { currentOperand = currentOperand.toString().slice(0, -1) } function appendNumber(number) { if (number === '.' && currentOperand.includes('.')) return currentOperand = currentOperand.toString() + number.toString() } // ...etc ...etc