最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Shortening function name with variable - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question asked Feb 14, 2013 at 3:39 vearutopvearutop 4,08226 silver badges42 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

When 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.

发布评论

评论列表(0)

  1. 暂无评论