Javascript 调用函数内部的外部声明变量

Javascript 调用函数内部的外部声明变量,javascript,angularjs,typescript,firebase,firebase-realtime-database,Javascript,Angularjs,Typescript,Firebase,Firebase Realtime Database,我编写了一个函数来检查firebase数据库中的“phonenumber”子项中是否保存了数据。。 考试顺利!但是在这个函数中,我不能调用外部声明的变量! 这是代码: phoneNumberExistence: boolean; FIREBASE_DATABASE.ref("Settings").child('phoneNumber').once('value', function(snapshot) { var exists = (snapshot.val() !== null)

我编写了一个函数来检查firebase数据库中的“phonenumber”子项中是否保存了数据。。 考试顺利!但是在这个函数中,我不能调用外部声明的变量! 这是代码:

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 :(");
      }
    })
有什么想法吗?
谢谢

使用箭头函数而不是
函数(快照){…}

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

箭头函数在词汇上绑定其上下文,因此这实际上是指原始上下文。有关更多详细信息,您可以阅读。

就我个人而言,我从不在Angular中使用
。坚持使用
$scope
。看,我不知道那种类型的函数,不管怎样,你的解决方案工作得很好,谢谢大家。这是EcmaScript 6的一个特性,因此您也可以在TypeScript中使用它。