Search code examples
javascriptshort

Smallest way to call a function


First, I was calling my functions like this:

var a=1;
a=foo(a,2);

Then I discovered prototype and called my functions like this:

var a=1;
a=a.foo(2);

And smaller if it's for arrays or objects:

var a=[1,2,3];
a.foo(2);

Is there a way to call functions like this: a(2) or a[2] with a hack or something?


Solution

  • You could do this;

    var a=[1,2,3];
    var m = "reallyLongMethodName";
    a[m](2);
    

    Which would call a.reallyLongMethodName(2) using square bracket notation.

    Things like this is possible in JavaScript:

    var a=[1,2,3];
    var c = a.foo;
    c(2);
    

    But, this won't work in your case as the this reference inside c would no longer be the array.

    You could fix this using call() or apply();

    c.call(a, 2);
    

    But that's probably too long for your liking.

    You could also create a wrapper function;

    function c(ar, val) {
        ar.foo(val);
    }
    
    c(a, 2);
    

    ... but again, that's probably too long for your liking ;).

    So all in all, what you've got is as short as it'll be... Congratulations. You've made your code as unreadable as possible.