Thomas Stock Thomas Stock - 5 months ago 7
Javascript Question

Using an object for function parameters

var foo = function(a, b, c) {

console.log(a);
console.log(b);
console.log(c.id);

};

//this works obviously
foo("a man", "b man", {id: "c.id man"});

var par = {
a: "a val",
b: "b cal",
c: {
id: "c.id val"
}
};


//can I make this work automatically?
foo(par);


Question is in code sample.

Can I automatically "unwrap" the par object to use the properties to fill in the function parameters?

Is there some kind of
foo(par.unwrap())
in javascript?

http://plnkr.co/edit/Y5M3qq7ROfaGGXrU21G5?p=preview

Answer

You can, but given that object properties are unordered it's a little hacky. The solution is to parse the function as a string to get the name of the parameters.

Here's a utility function :

function callunwrap(f,o){
    f.apply(null, (f.toString().match(/\([^\)]*\)/)[0].match(/\w+/g)||[]).map(function(name){
        return o[name];
    }));
}

Usage example

var foo = function(a, b, c) {
  console.log(a);
  console.log(b);
  console.log(c.id);
};

var par = {
  a: "a val",
  b: "b cal",
  c: {
    id: "c.id val"
  }
};


callunwrap(foo, par);

Now, as you see, callunwrap does a lot of things, I wouldn't recommend to use such a hacky thing in a real program. The usual non hacky solution is to have your function explicitly read the arguments :

var foo = function(o) {
  console.log(o.a);
  console.log(o.b);
  console.log(o.c.id);
};