ES6 defaults not available in .arguments?

If I have this declaration and an ES6 function call:

function myFunction (arg1, arg2 = "bob") { console.log("arguments", arguments); } myFunction(1); 

... the console.log() statement shows only one argument with a value of "1". "Bob" is nowhere to be seen. Is this expected and / or desired behavior? I would expect the default values ​​to be available in the arguments object. If not, is there a way to dynamically get all arguments + default values ​​in some other way?

Thanks in advance!

+7
javascript ecmascript-6
source share
2 answers

Yes, this is expected and desirable. The arguments object is a list of values ​​that were passed to the function, and nothing more.

It is not indirectly associated with parameter variables (which are assigned default values), as was the case in sloppy mode.

Is there a way to dynamically get all arguments + default values ​​in another way?

Not. What parameters you have and whether they are initializers by default are static, you do not need to do anything dynamically here. You can do Object.assign([], arguments, [arg1, arg2]) for your sample function.

+9
source share

As you already know, there is no built-in method for getting "passed arguments and default values ​​where arguments are not passed." But there is a workaround:

This function (which I found here ) receives all the parameters of this function:

 function getArgs(func) { var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1]; return args.split(',').map(function(arg) { return arg.replace(/\/\*.*\*\//, '').trim(); }).filter(function(arg) { return arg; }); }; 

So, combining this function with the arguments your myFunction function, we can get an array that has what you want:

 function myFunction (arg1, arg2 = "bob") { var thisArguments = arguments; console.log(getArgs(myFunction, thisArguments)); }; function getArgs(func, argums) { var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1]; var argsArray = args.split(',').map(function(arg) { return arg.replace(/\/\*.*\*\//, '').trim(); }).filter(function(arg) { return arg; }); for(var i = 0; i < argsArray.length; i++){ argsArray[i] += " (default)"; } var defaults = argsArray.slice(argums.length); argums = Array.prototype.slice.call(argums); return argums.concat(defaults); }; 

Now we can see the information in the console that calls myFunction :

1. Passing more arguments than parameters

This will return only the arguments.

 myFunction("foo", "bar", "baz"); //returns: ["foo", "bar", "baz"] 

2. Passing less arguments than parameters

It returns the arguments and default remainder parameters as you want (I added a "default" for each row).

 myFunction("foo"); //returns ["foo", "arg2 = "bob" (default)"] 

3. Passing arguments

This will return all parameters.

 myFunction(); //returns ["arg1 (default)", "arg2 = "bob" (default)"] 

This is the fiddle: https://jsfiddle.net/gerardofurtado/25jxrkm8/1/

+1
source share

All Articles