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.