首页 > 解决方案 > 有没有办法将特定行分配给经常使用的变量?

问题描述

在我的代码中经常使用 document.getElementById()。那么如果可能的话,有什么方法可以将这行长代码缩写为一个小变量?

标签: javascriptdom

解决方案


您可以使用包装函数,如:

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

阅读Function.bind的文档


推荐阅读