【问题标题】:Error assigning value to JavaScript class property为 JavaScript 类属性赋值时出错
【发布时间】: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


    【解决方案1】:

    您需要将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
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多