Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

javascript - Cannot read property 'input' of undefined

I have a function that get's the user's input. Inside that function, is a callback function that checks the user's input. When calling the call back function, i get an error, ERROR Error: Cannot read property '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);
  }
    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do one of three things:

  1. Make the function you pass (chkAns) atomic - that is, that it doesnt require a specific state (this.input, this.answer), and get those parameters when its called (so instead of chkAns(), you will do chkAns(this.input, this.answer)
  2. Don't pass it from the template, but call this.CheckAnswer() inside getInput
  3. Pass this contex to the chkAns when calling it: chkAns.call(this) - I think this option is the least "angularish" option

Here is a working stackblitz of the second option


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...