无法读取未定义的 属性 'input'
Cannot read property 'input' of undefined
我有一个获取用户输入的函数。在该函数内部,是一个检查用户输入的回调函数。调用回调函数时,出现错误,ERROR Error: Cannot read 属性 'input' of undefined.
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);
}
}
您可以做以下三件事之一:
- 使您传递的函数 (chkAns) 成为原子函数——也就是说,它不需要特定状态 (this.input、this.answer),并在调用时获取这些参数(因此而不是
chkAns()
,你会做chkAns(this.input, this.answer)
- 不要从模板传递,而是在
getInput
中调用this.CheckAnswer()
- 调用时将
this
contex 传递给 chkAns:chkAns.call(this)
- 我认为这个选项是最不“有棱角”的选项
这是第二个选项
的有效stackblitz
我有一个获取用户输入的函数。在该函数内部,是一个检查用户输入的回调函数。调用回调函数时,出现错误,ERROR Error: Cannot read 属性 'input' of undefined.
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);
}
}
您可以做以下三件事之一:
- 使您传递的函数 (chkAns) 成为原子函数——也就是说,它不需要特定状态 (this.input、this.answer),并在调用时获取这些参数(因此而不是
chkAns()
,你会做chkAns(this.input, this.answer)
- 不要从模板传递,而是在
getInput
中调用 - 调用时将
this
contex 传递给 chkAns:chkAns.call(this)
- 我认为这个选项是最不“有棱角”的选项
this.CheckAnswer()
这是第二个选项
的有效stackblitz