【问题标题】:Call external declared variable inside the function [duplicate]在函数内调用外部声明的变量[重复]
【发布时间】:2023-04-03 03:17:01
【问题描述】:

我编写了一个函数来检查我的 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 :(");
      }
    })

有什么想法吗? 谢谢

【问题讨论】:

标签: javascript angularjs typescript firebase firebase-realtime-database


【解决方案1】:

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

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

箭头函数在词法上绑定它们的上下文,所以 this 实际上是指原始上下文。更多详情可以阅读this article

【讨论】:

  • 我不知道那种类型的功能,无论如何你的解决方案工作得很好,谢谢伙计
  • 欢迎您。这是 EcmaScript 6 的一个特性,所以你也可以在 TypeScript 中使用它。
猜你喜欢
  • 1970-01-01
  • 2013-03-23
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 2015-02-10
  • 2019-02-08
相关资源
最近更新 更多