admin管理员组文章数量:1414605
I would like to call some functions by shorter alias in order to minimize code size.
(function(){
var t = document.getElementById;
t('element-id');
})();
This piece of code gives Error: Could not convert JavaScript argument
. Why?
I would like to call some functions by shorter alias in order to minimize code size.
(function(){
var t = document.getElementById;
t('element-id');
})();
This piece of code gives Error: Could not convert JavaScript argument
. Why?
3 Answers
Reset to default 4When you assign a function to a different variable, it's this
value changes. Since getElementById
expects this
to be an element, you're getting an error.
If you're in an environment where you can use bind
, use it:
(function(){
var t = document.getElementById.bind(document);
t('element-id');
})();
This'll ensure that t
's this
will stay the document
object.
If you can't use bind
, you'll have to create an intermediary function:
(function() {
function t (id) {
document.getElementById(id);
}
t('element-id');
})();
As Joseph says, the this
value changes and it messes up the function. Try the following:
var t = function(i) {return document.getElementById(i);};
so in this case, you could do
let t = (id) => document.getElementById(id);
t("myElement")
this implies use of an arrow function that returns the object just like document.getElementById("")
would.
本文标签: javascriptShortening function name with variableStack Overflow
版权声明:本文标题:javascript - Shortening function name with variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745182287a2646520.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论