为 JavaScript class 属性 赋值时出错
Error assigning value to JavaScript class property
我在 javascript class 中设置 class 属性 时出错。我正在使用 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
编辑:
设置 resultAge 的问题已解决,但现在的问题是 var age = a.displayTotalAge(); 在 console.log(age) 之后计算结果在 0;
您需要将 ageTotal
的范围传递给 prompt.get
回调:
var ageTotal = function(){
this.resultAge = 0;
this.getUserAge = function(){
var that = this;
prompt.start();
prompt.get(["age"], function(err, result){
that.resultAge += result.age
});
}
}
我在 javascript class 中设置 class 属性 时出错。我正在使用 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
编辑: 设置 resultAge 的问题已解决,但现在的问题是 var age = a.displayTotalAge(); 在 console.log(age) 之后计算结果在 0;
您需要将 ageTotal
的范围传递给 prompt.get
回调:
var ageTotal = function(){
this.resultAge = 0;
this.getUserAge = function(){
var that = this;
prompt.start();
prompt.get(["age"], function(err, result){
that.resultAge += result.age
});
}
}