【发布时间】:2015-05-08 15:33:47
【问题描述】:
在 javascript 类中设置类属性时出现错误。我正在使用 nodejs 提示模块来获取用户输入并将其设置为类属性。但我收到以下错误。
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
编辑: 问题设置 resultAge 已解决,但现在问题是 var age = a.displayTotalAge(); 在 console.log(age) 之后评估导致 0 ;
【问题讨论】:
标签: javascript node.js asynchronous synchronization prompt