【问题标题】:This keyword points to global object in class method?这个关键字指向类方法中的全局对象?
【发布时间】: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();
})
})

【问题讨论】:

    标签: class methods this


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2017-03-11
      • 2016-09-25
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多