javascript - Shortening function name with variable - Stack Overflow

I would like to call some functions by shorter alias in order to minimize code size.(function(){var t =

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745182287a4615473.html

相关推荐

  • javascript - Shortening function name with variable - Stack Overflow

    I would like to call some functions by shorter alias in order to minimize code size.(function(){var t =

    5小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信