javascript - 有没有办法将特定行分配给经常使用的变量?
问题描述
在我的代码中经常使用 document.getElementById()。那么如果可能的话,有什么方法可以将这行长代码缩写为一个小变量?
解决方案
您可以使用包装函数,如:
const byId = (id) => document.getElementById(id);
或者
通过将其与对象绑定来分配document.getElementById
给变量。document
const byId = document.getElementById.bind(document);
注意:在第二种方法中,如果你不绑定你会document.getElementById
得到document
错误:
Uncaught TypeError: Illegal invocation
Function.bind
它的作用是创建一个新函数,其关键字this
设置为您作为参数提供的值Function.bind
。
推荐阅读
- r - 将函数映射到两个长度不等的数据帧
- java - CustomClientDetailsService 在我的 AuthorizationServer 上运行 6 次
- react-native - Expo Android 请求被阻止
- python - 无法追加到现有表。默默地失败
- python - 组合 TSV 文件为 Apache Arrow 表创建新的 TSV
- c# - GET 请求 - androidpublisher.googleapis.com/androidpublisher/v3/ - 抛出 403 “调用者没有权限”
- python - 有没有办法在散点图中获取单个点的 x 和 y 坐标?
- python - Python 列出原始 Cloudwatch 指标值
- python - 由于 tclError,使用 tkinter 的 python 程序无法运行
- c++ - 使用 Eigen3 的 CGAL 程序编译错误