Is it possible to get the names of function arguments in JS?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
5 views
Is it possible to get the arguments as an array, to cycle, to create properties for the object?

function Worker(name, surname, rate, days) { this.name = name; this.surname = surname; this.rate = rate; this.days = days; Worker.prototype.getSalary = function() { return days * rate } var array = Object.keys(this); for (var i = 0; i < array.length; i++) { Object.defineProperty(this, array[i], { writable: false, configurable: false }); }; }
by | 5 views

2 Answers

0 like 0 dislike
Arguments stored in the arguments.
UPD:
The names of the arguments can get spike method. Stupidly breaking the string func.toString() the Other way, like no. Here googled this code
function getArgs(func) { // First match everything inside the function argument parens. var args = func.toString().match(/function\\s.*?\\(([^)]*)\\)/)[1]; // Split the argument string into an array, comma delimited. return args.split(',').map(function(arg) { // Ensure no inline comments are parsed and trim the whitespace. return arg.replace(/\\/\\*.*\\*\\//, ").trim(); }).filter(function(arg) { // Ensure no undefined values are added. return arg; }); } // Example function a(b,c) { } getArgs(a); // ['b', 'c']

Can combine this code with arguments to get the names and values.
function Worker(name, surname, rate, days) { var names = getArgs(Worker); for (var i = 0; i < names.length; i++) { var name = names[i]; var value = arguments[i]; console.warn(name, value); // Prints the parameter name and its value. // Value will be undefined if it is not transferred }; }

But it's stupid because the arguments are names only if they explicitly declared, or they simply have an index in the arguments. For these tasks it is better to use the object.
by
0 like 0 dislike
Worker function(params) { for (key in params) { this[key] = params[key]; } // ... } new Worker({ name : '123', surname : '123', rate : '123', days : '123', });
by

Related questions

0 like 0 dislike
3 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
35,573 users