我想通过更短的别名调用一些函数,以最小化代码大小。
(function(){
var t = document.getElementById;
t('element-id');
})();
这段代码给出了Error: Could not convert JavaScript argument
。为什么?
最佳答案
当您将函数分配给不同的变量时,它的this
值会发生变化。因为 getElementById
期望 this
是一个元素,所以你会得到一个错误。
如果您处于可以使用 bind
的环境中,使用它:
(function(){
var t = document.getElementById.bind(document);
t('element-id');
})();
这将确保 t
的 this
将保留为 document
对象。
如果不能使用bind
,则必须创建一个中间函数:
(function() {
function t (id) {
document.getElementById(id);
}
t('element-id');
})();
关于javascript - 用变量缩短函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867417/