在函数内更新时未定义的变量

Variable undefined when updated inside a function

本文关键字:未定义 变量 更新 函数      更新时间:2023-09-26

我在函数之外声明user_properties。然后,我从Firebase获取数据并尝试将其存储在user_properties中,但最终未定义。

有谁知道我在这里做错了什么?

var user_properties;
get_user_properties = new Firebase("https://<MY-URL>/users/"+auth.uid+"/properties");
get_user_properties.once('value', function (dataSnapshot) {
  user_properties = dataSnapshot.val();
});
//undefined
console.log(user_properties);

我为您提供了一个简单的示例。

var foo,
    obj = new Bar("some text");
obj.set("cute cat", function(cat){
    foo = "my lovely cat";
});
console.log(foo); // undefined
obj.doo();
console.log(foo); // "my lovely cat"

使用此构造函数

function Bar(c){
    this.mcat = c;
    this.callback;
    /* this method only saves that callback function */
    this.set = function(catname, callback){
        this.mcat = catname;
        this.callback = callback;
    }
    /* this method calls that callback function */
    this.doo = function(){
        this.callback();
    }
}