首页 > 解决方案 > 在函数内部调用外部声明的变量

问题描述

我写了一个函数来检查我的firebase数据库中是否有数据保存在“phonenumber”子项中......测试是OKEY!但是在这个函数里面我不能调用一个外部声明的变量!这是代码:

phoneNumberExistence: boolean;

FIREBASE_DATABASE.ref("Settings").child('phoneNumber').once('value', function(snapshot) {
      var exists = (snapshot.val() !== null);
      //console.log("Phone number existance: "+exists);
      if(exists){
        this.phoneNumberExistence = true; //the problem is here.. can't use this variable
        console.log("A phone number already exists.")
      }
      else{
        this.phoneNumberExistence = false; //the problem is here.. can't use this variable
        console.log("There is no phone number here :(");
      }
    })

任何想法 ?谢谢

标签: javascriptangularjstypescriptfirebasefirebase-realtime-database

解决方案


使用箭头函数代替function(snapshot) {...}

... .once('value', (snapshot) => {
  var exists = (snapshot.val() !== null);
  ...
});

箭头函数在词法上绑定它们的上下文,因此 this 实际上是指原始上下文。有关更多详细信息,您可以阅读这篇文章


推荐阅读