【问题标题】:Cannot read property 'input' of undefined无法读取未定义的属性“输入”
【发布时间】:2021-01-16 12:27:04
【问题描述】:

我有一个获取用户输入的函数。在该函数内部,是一个检查用户输入的回调函数。调用回调函数时,出现错误,ERROR 错误:无法读取未定义的属性“输入”。

HTML

<input id="answer" type="number" (input)= "getInput($event, checkAnswer)" >

JS

input = null;
answer = null;


getInput(event, chkAns){

this.input = Number(event.target.value);

chkAns();

console.log("Input :" + " " + this.input);

 }

 checkAnswer(){

  if(this.input === this.answer){
  
    this.multiply();

  } else{

     console.log(this.input + " " + "is incorrect" + " "  + typeof 
     this.answer);
  }
    
}

【问题讨论】:

  • 可能是因为this 在该上下文中未定义。
  • 你能否在你的问题中加入一个有效的 sn-p - 特别是展示如何调用 getInput 以及 chkAns 和 checkAnswer 之间的关系。
  • @AHaworth 链接:app-x.stackblitz.io

标签: javascript angular error-handling undefined


【解决方案1】:

您可以做以下三件事之一:

  1. 使您传递的函数 (chkAns) 具有原子性 - 也就是说,它不需要特定的状态(this.input、this.answer),并在调用时获取这些参数(因此,您将代替 chkAns()chkAns(this.input, this.answer)
  2. 不要从模板中传递它,而是在getInput 中调用this.CheckAnswer()
  3. 在调用它时将 this contex 传递给 chkAns:chkAns.call(this) - 我认为这个选项是最不“棱角分明”的选项

这是 second 选项的工作 stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多