javascript - 在函数内部调用外部声明的变量
问题描述
我写了一个函数来检查我的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 :(");
}
})
任何想法 ?谢谢
解决方案
使用箭头函数代替function(snapshot) {...}
... .once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
...
});
箭头函数在词法上绑定它们的上下文,因此 this 实际上是指原始上下文。有关更多详细信息,您可以阅读这篇文章。
推荐阅读
- python - 使用第二个键对嵌套字典进行排序
- angular - 从动态创建的子组件向父组件发出事件
- python - 如何使用数据框中的前两行作为python中的列索引
- c# - 为什么我的匿名对象在单元测试中没有集合,但在实际应用程序中工作正常?
- jquery - 如何在点击时更改其他列表项的不透明度?
- javascript - 在 Angular/客户端项目中使用转换为 JavaScript 的 Kotlin 代码
- java - 在二维数组中打印中间行和列
- python - 输入数字时需要帮助制作按钮以执行 for 循环
- typescript - 分配类型以匹配变量类型
- python - 如何创建单窗口 GUI