Is there a way to retrieve a function\'s default argument value in JavaScript?
function foo(x = 5) {
// things I do not control
}
Is th
I'd tackle it by extracting the parameters from a string version of the function:
// making x=3 into {x: 3}
function serialize(args) {
var obj = {};
var noWhiteSpace = new RegExp(" ", "g");
args = args.split(",");
args.forEach(function(arg) {
arg = arg.split("=");
var key = arg[0].replace(noWhiteSpace, "");
obj[key] = arg[1];
});
return obj;
}
function foo(x=5, y=7, z='foo') {}
// converting the function into a string
var fn = foo.toString();
// magic regex to extract the arguments
var args = /\(\s*([^)]+?)\s*\)/.exec(fn);
//getting the object
var argMap = serialize(args[1]); // {x: "5", y: "7", z: "'foo'"}
argument extraction method was taken from here: Regular Expression to get parameter list from function definition
cheers!
PS. as you can see, it casts integers into strings, which can be annoying at times. just make sure you know the input type beforehand or make sure it won't matter.