0

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Paul Nikonowicz
  • 3,883
  • 21
  • 39

1 Answers1

1

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;
}
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134