这个关键字指向类方法中的全局对象吗?

时间:2019-07-05 06:01:51

标签: class methods this

我正在使用一个类来构建计算器。现在,我正在测试以查看何时按下数字按钮,它将显示出来。它没有错误。未捕获的TypeError:无法设置未定义的属性'innerText'。 现在,当我在updateDisplay方法中删除此关键字时,一切正常吗?好像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();
})
})

1 个答案:

答案 0 :(得分:0)

抱歉,构造函数拼写错误。