为JavaScript类属性赋值时出错

Error assigning value to JavaScript class property

本文关键字:出错 赋值 属性 JavaScript      更新时间:2023-09-26

在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(年龄)之后进行评估,结果为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
        });
    }
}