javascript - 是否可以在 Javascript 中动态添加方法?
问题描述
嘿,我正在做一个如下所示的 firebase 数据库调用:
db.collection("posts").where("location", "==", location)
.get().then((querySnapshot) => {
[...]
})
用户可以指定他想从哪些国家获得帖子(.where()
方法就是为此)。但他也可以选择所有国家,所以在这种情况下不再需要该方法。有没有办法动态添加方法?
像这样的东西:
db.collection("posts")if(location != "all"){.where("location", "==", location)}
.get().then((querySnapshot) => {
[...]
})
解决方案
你可以使用一个函数
const addLocationCondition = (collection, location) =>
location === "all" ? collection : collection.where('location', '==', location);
addLocationCondition(db.collection('posts'), location).get()...
推荐阅读
- android - 我的按钮没有采用背景颜色
- ruby-on-rails - Rails 用守卫替换 if/elseif 块
- javascript - Vue.js - 使用外部脚本而不是导入的脚本
- google-apps-script - 谷歌脚本将没有 URL 的图像插入到谷歌表格
- java - 如何解决“索引越界错误”?
- python-3.x - Jupyter 安装环境
- reactjs - 材质 UI 禁用复选框悬停
- css - position: fixed 不占空间,下面怎么加?
- django - 无法使用 Django 在 HTML 中插入类别标题
- javascript - 如何制作显示在列表中最后一个警报元素中的扩展?