Paul Nikonowicz
Paul Nikonowicz

Reputation: 3903

apply arguments to function

I would like to apply arguments represented as a hash to a function.

For example, I would like to call this function:

myFunc = function(a,b,c) { return b }

In a way similiar to this:

myFunc({a:1, b:2, c:3})

Is there a way to do this in javascript?

Upvotes: 0

Views: 91

Answers (1)

Platinum Azure
Platinum Azure

Reputation: 46183

It's not possible to associate positional arguments in a function with key-value pairs in an object in general.

It is possible to configure a function to take arguments both ways:

myFunc = function (objOrA, b, c) {
    var a = objOrA;
    if (objOrA.a || objOrA.b || objOrA.c) {
        a = objOrA.a;
        b || (b = objOrA.b);
        c || (c = objOrA.c);
    }
    return b;
};

If you have control over the function definition, however, the simplest solution is simply to require an object as the sole parameter no matter what.

myFunc = function (options) {
    return options.b;
}

Upvotes: 1

Related Questions