在javascript类中设置类属性时出错。我使用nodejs提示模块获取用户输入并将其设置为class属性。但我遇到了以下错误。
TypeError:无法读取未定义的属性“resultAge”
我发现这与
同步,同步
,但我无法弄清楚如何在这种情况下实施它。
此外,我想再次提示用户,直到他输入了一个有效的数字(我不能使用do-while循环,可能的解决方案是什么?)
var prompt = require("prompt");
var ageTotal = function(){
this.resultAge = 0;
this.getUserAge = function(){
prompt.start();
//i want to run this until valid input is entered
prompt.get(["age"], function(err, result){
//I know i have to convert userInput to int but thats for later
this.resultAge += result.age
});
}
}
ageTotal.prototype.displayTotalAge = function(){
return this.resultAge;
}
var a = new ageTotal();
a.getUserAge();
var age = a.displayTotalAge();
console.log(age); //This is running before the above function finishes
编辑:
问题设置结果年龄已解决,但现在问题是
var age=a.displayTotalAge();
在console.log(age)之后进行评估,这将导致
0
;