【发布时间】:2019-07-05 06:01:51
【问题描述】:
我正在使用一个类构建一个计算器。现在我正在测试,看看我什么时候点击了一个数字按钮,它会被显示出来。它没有错误。未捕获的类型错误:无法设置未定义的属性“innerText”。 现在,当我在 updateDisplay 方法中删除 this 关键字时,一切正常吗?好像 this 关键字指向全局对象?这里发生了什么?
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const equalsButton = document.querySelector('[data-equals]');
const deleteButton = document.querySelector('[data-delete]');
const allClearButton = document.querySelector('[data-all-clear]');
const previousOperandTextElement = document.querySelector('[data-previous-
operand]');
const currentOperandTextElement = document.querySelector('[data-current-
operand]');
class Calculator {
contructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear();
}
clear() {
this.currentOperand = '';
this.previousOperand = '';
this.operation = undefined;
}
delete(){
}
appendNumber(number) {
this.currentOperand = number;
}
chooseOperation(operation) {
}
compute() {
}
updateDisplay() {
this.currentOperandTextElement.innerText = this.currentOperand;
/* the code above throws an error, below works fine, so without the
this keyword? */
currentOperandTextElement.innerText = this.currentOperand;
}
}
const calculator = new Calculator(previousOperandTextElement,
currentOperandTextElement);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText)
calculator.updateDisplay();
})
})
【问题讨论】: