Hướng dẫn get parameter name javascript

The following function will return an array of the parameter names of any function passed in.

var STRIP_COMMENTS = /[[\/\/.*$]|[\/\*[\s\S]*?\*\/]]/mg;
var ARGUMENT_NAMES = /[[^\s,]+]/g;
function getParamNames[func] {
  var fnStr = func.toString[].replace[STRIP_COMMENTS, ''];
  var result = fnStr.slice[fnStr.indexOf['[']+1, fnStr.indexOf[']']].match[ARGUMENT_NAMES];
  if[result === null]
     result = [];
  return result;
}

Example usage:

getParamNames[getParamNames] // returns ['func']
getParamNames[function [a,b,c,d]{}] // returns ['a','b','c','d']
getParamNames[function [a,/*b,c,*/d]{}] // returns ['a','d']
getParamNames[function []{}] // returns []

Edit:

With the invent of ES6 this function can be tripped up by default parameters. Here is a quick hack which should work in most cases:

var STRIP_COMMENTS = /[\/\/.*$]|[\/\*[\s\S]*?\*\/]|[\s*=[^,\]]*[['[?:\\'|[^'\r\n]]*']|["[?:\\"|[^"\r\n]]*"]]|[\s*=[^,\]]*]]/mg;

I say most cases because there are some things that will trip it up

function [a=4*[5/3], b] {} // returns ['a']

Edit: I also note vikasde wants the parameter values in an array also. This is already provided in a local variable named arguments.

excerpt from //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments:

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

var args = Array.prototype.slice.call[arguments];

If Array generics are available, one can use the following instead:

var args = Array.slice[arguments];

answered Mar 29, 2012 at 11:30

Jack AllanJack Allan

14k11 gold badges43 silver badges55 bronze badges

26

Below is the code taken from AngularJS which uses the technique for its dependency injection mechanism.

And here is an explanation of it taken from //docs.angularjs.org/tutorial/step_05

Angular's dependency injector provides services to your controller when the controller is being constructed. The dependency injector also takes care of creating any transitive dependencies the service may have [services often depend upon other services].

Note that the names of arguments are significant, because the injector uses these to look up the dependencies.

/**
 * @ngdoc overview
 * @name AUTO
 * @description
 *
 * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
 */

var FN_ARGS = /^function\s*[^\[]*\[\s*[[^\]]*]\]/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*[_?][.+?]\1\s*$/;
var STRIP_COMMENTS = /[[\/\/.*$]|[\/\*[\s\S]*?\*\/]]/mg;
function annotate[fn] {
  var $inject,
      fnText,
      argDecl,
      last;

  if [typeof fn == 'function'] {
    if [![$inject = fn.$inject]] {
      $inject = [];
      fnText = fn.toString[].replace[STRIP_COMMENTS, ''];
      argDecl = fnText.match[FN_ARGS];
      forEach[argDecl[1].split[FN_ARG_SPLIT], function[arg]{
        arg.replace[FN_ARG, function[all, underscore, name]{
          $inject.push[name];
        }];
      }];
      fn.$inject = $inject;
    }
  } else if [isArray[fn]] {
    last = fn.length - 1;
    assertArgFn[fn[last], 'fn']
    $inject = fn.slice[0, last];
  } else {
    assertArgFn[fn, 'fn', true];
  }
  return $inject;
}

answered Aug 24, 2012 at 11:39

LambderLambder

2,8621 gold badge25 silver badges20 bronze badges

7

Here is an updated solution that attempts to address all the edge cases mentioned above in a compact way:

function $args[func] {  
    return [func + '']
      .replace[/[/][/].*$/mg,''] // strip single-line comments
      .replace[/\s+/g, ''] // strip white space
      .replace[/[/][*][^/*]*[*][/]/g, ''] // strip multi-line comments  
      .split[']{', 1][0].replace[/^[^[]*[[]/, ''] // extract the parameters  
      .replace[/=[^,]+/g, ''] // strip any ES6 defaults  
      .split[','].filter[Boolean]; // split & filter [""]
}  

Abbreviated test output [full test cases are attached below]:

'function [a,b,c]...' // returns ["a","b","c"]
'function []...' // returns []
'function named[a, b, c] ...' // returns ["a","b","c"]
'function [a /* = 1 */, b /* = true */] ...' // returns ["a","b"]
'function fprintf[handle, fmt /*, ...*/] ...' // returns ["handle","fmt"]
'function[ a, b = 1, c ]...' // returns ["a","b","c"]
'function [a=4*[5/3], b] ...' // returns ["a","b"]
'function [a, // single-line comment xjunk] ...' // returns ["a","b"]
'function [a /* fooled you...' // returns ["a","b"]
'function [a /* function[] yes */, \n /* no, */b]/* omg! */...' // returns ["a","b"]
'function [ A, b \n,c ,d \n ] \n ...' // returns ["A","b","c","d"]
'function [a,b]...' // returns ["a","b"]
'function $args[func] ...' // returns ["func"]
'null...' // returns ["null"]
'function Object[] ...' // returns []

answered Jul 2, 2015 at 21:28

humbletimhumbletim

1,06811 silver badges10 bronze badges

9

Solution that is less error prone to spaces and comments would be:

var fn = function[/* whoa] */ hi, you]{};

fn.toString[]
  .replace[/[[\/\/.*$]|[\/\*[\s\S]*?\*\/]|[\s]]/mg,'']
  .match[/^function\s*[^\[]*\[\s*[[^\]]*]\]/m][1]
  .split[/,/]

["hi", "you"]

answered Feb 2, 2013 at 8:26

buberssonbubersson

7591 gold badge6 silver badges12 bronze badges

1

A lot of the answers on here use regexes, this is fine but it doesn't handle new additions to the language too well [like arrow functions and classes]. Also of note is that if you use any of these functions on minified code it's going to go 🔥. It will use whatever the minified name is. Angular gets around this by allowing you to pass in an ordered array of strings that matches the order of the arguments when registering them with the DI container. So on with the solution:

var esprima = require['esprima'];
var _ = require['lodash'];

const parseFunctionArguments = [func] => {
    // allows us to access properties that may or may not exist without throwing 
    // TypeError: Cannot set property 'x' of undefined
    const maybe = [x] => [x || {}];

    // handle conversion to string and then to JSON AST
    const functionAsString = func.toString[];
    const tree = esprima.parse[functionAsString];
    console.log[JSON.stringify[tree, null, 4]]
    // We need to figure out where the main params are. Stupid arrow functions 👊
    const isArrowExpression = [maybe[_.first[tree.body]].type == 'ExpressionStatement'];
    const params = isArrowExpression ? maybe[maybe[_.first[tree.body]].expression].params 
                                     : maybe[_.first[tree.body]].params;

    // extract out the param names from the JSON AST
    return _.map[params, 'name'];
};

This handles the original parse issue and a few more function types [e.g. arrow functions]. Here's an idea of what it can and can't handle as is:

// I usually use mocha as the test runner and chai as the assertion library
describe['Extracts argument names from function signature. 💪', [] => {
    const test = [func] => {
        const expectation = ['it', 'parses', 'me'];
        const result = parseFunctionArguments[toBeParsed];
        result.should.equal[expectation];
    } 

    it['Parses a function declaration.', [] => {
        function toBeParsed[it, parses, me]{};
        test[toBeParsed];
    }];

    it['Parses a functional expression.', [] => {
        const toBeParsed = function[it, parses, me]{};
        test[toBeParsed];
    }];

    it['Parses an arrow function', [] => {
        const toBeParsed = [it, parses, me] => {};
        test[toBeParsed];
    }];

    // ================= cases not currently handled ========================

    // It blows up on this type of messing. TBH if you do this it deserves to 
    // fail 😋 On a tech note the params are pulled down in the function similar 
    // to how destructuring is handled by the ast.
    it['Parses complex default params', [] => {
        function toBeParsed[it=4*[5/3], parses, me] {}
        test[toBeParsed];
    }];

    // This passes back ['_ref'] as the params of the function. The _ref is a 
    // pointer to an VariableDeclarator where the ✨🦄 happens.
    it['Parses object destructuring param definitions.' [] => {
        function toBeParsed [{it, parses, me}]{}
        test[toBeParsed];
    }];

    it['Parses object destructuring param definitions.' [] => {
        function toBeParsed [[it, parses, me]]{}
        test[toBeParsed];
    }];

    // Classes while similar from an end result point of view to function
    // declarations are handled completely differently in the JS AST. 
    it['Parses a class constructor when passed through', [] => {
        class ToBeParsed {
            constructor[it, parses, me] {}
        }
        test[ToBeParsed];
    }];
}];

Depending on what you want to use it for ES6 Proxies and destructuring may be your best bet. For example if you wanted to use it for dependency injection [using the names of the params] then you can do it as follows:

class GuiceJs {
    constructor[] {
        this.modules = {}
    }
    resolve[name] {
        return this.getInjector[][this.modules[name]];
    }
    addModule[name, module] {
        this.modules[name] = module;
    }
    getInjector[] {
        var container = this;

        return [klass] => {
            console.log[klass];
            var paramParser = new Proxy[{}, {
                // The `get` handler is invoked whenever a get-call for
                // `injector.*` is made. We make a call to an external service
                // to actually hand back in the configured service. The proxy
                // allows us to bypass parsing the function params using
                // taditional regex or even the newer parser.
                get: [target, name] => container.resolve[name],

                // You shouldn't be able to set values on the injector.
                set: [target, name, value] => {
                    throw new Error[`Don't try to set ${name}! 😑`];
                }
            }]
            return new klass[paramParser];
        }
    }
}

It's not the most advanced resolver out there but it gives an idea of how you can use a Proxy to handle it if you want to use args parser for simple DI. There is however one slight caveat in this approach. We need to use destructuring assignments instead of normal params. When we pass in the injector proxy the destructuring is the same as calling the getter on the object.

class App {
   constructor[{tweeter, timeline}] {
        this.tweeter = tweeter;
        this.timeline = timeline;
    }
}

class HttpClient {}

class TwitterApi {
    constructor[{client}] {
        this.client = client;
    }
}

class Timeline {
    constructor[{api}] {
        this.api = api;
    }
}

class Tweeter {
    constructor[{api}] {
        this.api = api;
    }
}

// Ok so now for the business end of the injector!
const di = new GuiceJs[];

di.addModule['client', HttpClient];
di.addModule['api', TwitterApi];
di.addModule['tweeter', Tweeter];
di.addModule['timeline', Timeline];
di.addModule['app', App];

var app = di.resolve['app'];
console.log[JSON.stringify[app, null, 4]];

This outputs the following:

{
    "tweeter": {
        "api": {
            "client": {}
        }
    },
    "timeline": {
        "api": {
            "client": {}
        }
    }
}

Its wired up the entire application. The best bit is that the app is easy to test [you can just instantiate each class and pass in mocks/stubs/etc]. Also if you need to swap out implementations, you can do that from a single place. All this is possible because of JS Proxy objects.

Note: There is a lot of work that would need to be done to this before it would be ready for production use but it does give an idea of what it would look like.

It's a bit late in the answer but it may help others who are thinking of the same thing. 👍

answered Jan 7, 2017 at 18:57

James DrewJames Drew

5885 silver badges9 bronze badges

0

I know this is an old question, but beginners have been copypasting solutions that extract parameter names from the string representation of a function as if this was good practice in any code. Most of the time, this just hides a flaw in the logic.

Writing parameter names in the parentheses of a function declaration can be seen as a shorthand syntax for variable creation. This:

function doSomething[foo, bar] {
    console.log["does something"];
}

...is akin to this:

function doSomething[] {
    var foo = arguments[0];
    var bar = arguments[1];

    console.log["does something"];
}

The variables themselves are stored in the function's scope, not as properties in an object. Just like you can't manipulate the name of a variable with code, there is no way to retrieve the name of a parameter as it is not a string, and it could be eliminated during JIT compilation.

I always thought of the string representation of a function as a tool for debugging purposes, especially because of this arguments array-like object. You are not required to give names to the arguments in the first place. If you try parsing a stringified function, it doesn't actually tell you about extra unnamed parameters it might take.

Here's an even worse and more common situation. If a function has more than 3 or 4 arguments, it might be logical to pass it an object instead, which is easier to work with.

function saySomething[obj] {
  if[obj.message] console.log[[obj.sender || "Anon"] + ": " + obj.message];
}

saySomething[{sender: "user123", message: "Hello world"}];

In this case, the function itself will be able to read through the object it receives and look for its properties and get both their names and values, but trying to parse the string representation of the function would only give you "obj" for parameters, which isn't useful at all.

answered Aug 20, 2015 at 2:19

DominoDomino

5,91134 silver badges57 bronze badges

6

I have read most of the answers here, and I would like to add my one-liner.

new RegExp['[?:'+Function.name+'\\s*|^]\\[[.*?]\\]'].exec[Function.toString[].replace[/\n/g, '']][1].replace[/\/\*.*?\*\//g, ''].replace[/ /g, '']

or

function getParameters[func] {
  return new RegExp['[?:'+func.name+'\\s*|^]\\s*\\[[.*?]\\]'].exec[func.toString[].replace[/\n/g, '']][1].replace[/\/\*.*?\*\//g, ''].replace[/ /g, ''];
}

or for a one-liner function in ECMA6

var getParameters = func => new RegExp['[?:'+func.name+'\\s*|^]\\s*\\[[.*?]\\]'].exec[func.toString[].replace[/\n/g, '']][1].replace[/\/\*.*?\*\//g, ''].replace[/ /g, ''];

__

Let's say you have a function

function foo[abc, def, ghi, jkl] {
  //code
}

The below code will return "abc,def,ghi,jkl"

That code will also work with the setup of a function that Camilo Martin gave:

function  [  A,  b
,c      ,d
]{}

Also with Bubersson's comment on Jack Allan's answer:

function[a /* fooled you]*/,b]{}

__

Explanation

new RegExp['[?:'+Function.name+'\\s*|^]\\s*\\[[.*?]\\]']

This creates a Regular Expression with the new RegExp['[?:'+Function.name+'\\s*|^]\\s*\\[[.*?]\\]']. I have to use new RegExp because I am injecting a variable [Function.name, the name of the function being targeted] into the RegExp.

Example If the function name is "foo" [function foo[]], the RegExp will be /foo\s*\[[.*?]\]/.

Function.toString[].replace[/\n/g, '']

Then it converts the entire function into a string, and removes all newlines. Removing newlines helps with the function setup Camilo Martin gave.

.exec[...][1]

This is the RegExp.prototype.exec function. It basically matches the Regular Exponent [new RegExp[]] into the String [Function.toString[]]. Then the [1] will return the first Capture Group found in the Regular Exponent [[.*?]].

.replace[/\/\*.*?\*\//g, ''].replace[/ /g, '']

This will remove every comment inside /* and */, and remove all spaces.

This also now supports reading and understanding arrow [=>] functions, such as f = [a, b] => void 0;, in which Function.toString[] would return [a, b] => void 0 instead of the normal function's function f[a, b] { return void 0; }. The original regular expression would have thrown an error in its confusion, but is now accounted for.

The change was from new RegExp[Function.name+'\\s*\\[[.*?]\\]'] [/Function\s*\[[.*?]\]/] to new RegExp['[?:'+Function.name+'\\s*|^]\\[[.*?]\\]'] [/[?:Function\s*|^]\[[.*?]\]/]

If you want to make all the parameters into an Array instead of a String separated by commas, at the end just add .split[','].

answered Aug 31, 2016 at 15:42

ZomoXYZZomoXYZ

1,62418 silver badges43 bronze badges

5

Since JavaScript is a scripting language, I feel that its introspection should support getting function parameter names. Punting on that functionality is a violation of first principles, so I decided to explore the issue further.

That led me to this question but no built-in solutions. Which led me to this answer which explains that arguments is only deprecated outside the function, so we can no longer use myFunction.arguments or we get:

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

Time to roll up our sleeves and get to work:

⭐ Retrieving function parameters requires a parser because complex expressions like 4*[5/3] can be used as default values. So Gaafar's answer or James Drew's answer are so far the best approaches.

I tried the babylon and esprima parsers but unfortunately they can't parse standalone anonymous functions, as pointed out in Mateusz Charytoniuk's answer. I figured out another workaround though by surrounding the code in parentheses, so as not to change the logic:

const ast = parser.parse["[\n" + func.toString[] + "\n]"]

The newlines prevent issues with // [single-line comments].

⭐ If a parser is not available, the next-best option is to use a tried-and-true technique like Angular.js's dependency injector regular expressions. I combined a functional version of Lambder's answer with humbletim's answer and added an optional ARROW boolean for controlling whether ES6 fat arrow functions are allowed by the regular expressions.

Here are two solutions I put together. Note that these have no logic to detect whether a function has valid syntax, they only extract the arguments. This is generally ok since we usually pass parsed functions to getArguments[] so their syntax is already valid.

I will try to curate these solutions as best I can, but without effort from the JavaScript maintainers, this will remain an open problem.

Node.js version [not runnable until StackOverflow supports Node.js]:

const parserName = 'babylon';
// const parserName = 'esprima';
const parser = require[parserName];

function getArguments[func] {
    const maybe = function [x] {
        return x || {}; // optionals support
    }

    try {
        const ast = parser.parse["[\n" + func.toString[] + "\n]"];
        const program = parserName == 'babylon' ? ast.program : ast;

        return program
            .body[0]
            .expression
            .params
            .map[function[node] {
                return node.name || maybe[node.left].name || '...' + maybe[node.argument].name;
            }];
    } catch [e] {
        return []; // could also return null
    }
};

////////// TESTS //////////

function logArgs[func] {
	let object = {};

	object[func] = getArguments[func];

	console.log[object];
// 	console.log[/*JSON.stringify[*/getArguments[func]/*]*/];
}

console.log[''];
console.log['////////// MISC //////////'];

logArgs[[a, b] => {}];
logArgs[[a, b = 1] => {}];
logArgs[[a, b, ...args] => {}];
logArgs[function[a, b, ...args] {}];
logArgs[function[a, b = 1, c = 4 * [5 / 3], d = 2] {}];
logArgs[async function[a, b, ...args] {}];
logArgs[function async[a, b, ...args] {}];

console.log[''];
console.log['////////// FUNCTIONS //////////'];

logArgs[function[a, b, c] {}];
logArgs[function[] {}];
logArgs[function named[a, b, c] {}];
logArgs[function[a /* = 1 */, b /* = true */] {}];
logArgs[function fprintf[handle, fmt /*, ...*/] {}];
logArgs[function[a, b = 1, c] {}];
logArgs[function[a = 4 * [5 / 3], b] {}];
// logArgs[function [a, // single-line comment xjunk] {}];
// logArgs[function [a /* fooled you {}];
// logArgs[function [a /* function[] yes */, \n /* no, */b]/* omg! */ {}];
// logArgs[function [ A, b \n,c ,d \n ] \n {}];
logArgs[function[a, b] {}];
logArgs[function $args[func] {}];
logArgs[null];
logArgs[function Object[] {}];

console.log[''];
console.log['////////// STRINGS //////////'];

logArgs['function [a,b,c] {}'];
logArgs['function [] {}'];
logArgs['function named[a, b, c] {}'];
logArgs['function [a /* = 1 */, b /* = true */] {}'];
logArgs['function fprintf[handle, fmt /*, ...*/] {}'];
logArgs['function[ a, b = 1, c ] {}'];
logArgs['function [a=4*[5/3], b] {}'];
logArgs['function [a, // single-line comment xjunk] {}'];
logArgs['function [a /* fooled you {}'];
logArgs['function [a /* function[] yes */, \n /* no, */b]/* omg! */ {}'];
logArgs['function [ A, b \n,c ,d \n ] \n {}'];
logArgs['function [a,b] {}'];
logArgs['function $args[func] {}'];
logArgs['null'];
logArgs['function Object[] {}'];

Full working example:

//repl.it/repls/SandybrownPhonyAngles

Browser version [note that it stops at the first complex default value]:

function getArguments[func] {
    const ARROW = true;
    const FUNC_ARGS = ARROW ? /^[function]?\s*[^\[]*\[\s*[[^\]]*]\]/m : /^[function]\s*[^\[]*\[\s*[[^\]]*]\]/m;
    const FUNC_ARG_SPLIT = /,/;
    const FUNC_ARG = /^\s*[_?][.+?]\1\s*$/;
    const STRIP_COMMENTS = /[[\/\/.*$]|[\/\*[\s\S]*?\*\/]]/mg;

    return [[func || ''].toString[].replace[STRIP_COMMENTS, ''].match[FUNC_ARGS] || ['', '', '']][2]
        .split[FUNC_ARG_SPLIT]
        .map[function[arg] {
            return arg.replace[FUNC_ARG, function[all, underscore, name] {
                return name.split['='][0].trim[];
            }];
        }]
        .filter[String];
}

////////// TESTS //////////

function logArgs[func] {
	let object = {};

	object[func] = getArguments[func];

	console.log[object];
// 	console.log[/*JSON.stringify[*/getArguments[func]/*]*/];
}

console.log[''];
console.log['////////// MISC //////////'];

logArgs[[a, b] => {}];
logArgs[[a, b = 1] => {}];
logArgs[[a, b, ...args] => {}];
logArgs[function[a, b, ...args] {}];
logArgs[function[a, b = 1, c = 4 * [5 / 3], d = 2] {}];
logArgs[async function[a, b, ...args] {}];
logArgs[function async[a, b, ...args] {}];

console.log[''];
console.log['////////// FUNCTIONS //////////'];

logArgs[function[a, b, c] {}];
logArgs[function[] {}];
logArgs[function named[a, b, c] {}];
logArgs[function[a /* = 1 */, b /* = true */] {}];
logArgs[function fprintf[handle, fmt /*, ...*/] {}];
logArgs[function[a, b = 1, c] {}];
logArgs[function[a = 4 * [5 / 3], b] {}];
// logArgs[function [a, // single-line comment xjunk] {}];
// logArgs[function [a /* fooled you {}];
// logArgs[function [a /* function[] yes */, \n /* no, */b]/* omg! */ {}];
// logArgs[function [ A, b \n,c ,d \n ] \n {}];
logArgs[function[a, b] {}];
logArgs[function $args[func] {}];
logArgs[null];
logArgs[function Object[] {}];

console.log[''];
console.log['////////// STRINGS //////////'];

logArgs['function [a,b,c] {}'];
logArgs['function [] {}'];
logArgs['function named[a, b, c] {}'];
logArgs['function [a /* = 1 */, b /* = true */] {}'];
logArgs['function fprintf[handle, fmt /*, ...*/] {}'];
logArgs['function[ a, b = 1, c ] {}'];
logArgs['function [a=4*[5/3], b] {}'];
logArgs['function [a, // single-line comment xjunk] {}'];
logArgs['function [a /* fooled you {}'];
logArgs['function [a /* function[] yes */, \n /* no, */b]/* omg! */ {}'];
logArgs['function [ A, b \n,c ,d \n ] \n {}'];
logArgs['function [a,b] {}'];
logArgs['function $args[func] {}'];
logArgs['null'];
logArgs['function Object[] {}'];

Full working example:

//repl.it/repls/StupendousShowyOffices

answered Mar 28, 2018 at 21:18

Zack MorrisZack Morris

4,5912 gold badges52 silver badges80 bronze badges

4

[function[a,b,c]{}].toString[].replace[/.*\[|\].*/ig,""].split[',']

=> [ "a", "b", "c" ]

answered Aug 2, 2013 at 7:19

WillWill

2,4142 gold badges16 silver badges14 bronze badges

1

You can also use "esprima" parser to avoid many issues with comments, whitespace and other things inside parameters list.

function getParameters[yourFunction] {
    var i,
        // safetyValve is necessary, because sole "function [] {...}"
        // is not a valid syntax
        parsed = esprima.parse["safetyValve = " + yourFunction.toString[]],
        params = parsed.body[0].expression.right.params,
        ret = [];

    for [i = 0; i < params.length; i += 1] {
        // Handle default params. Exe: function defaults[a = 0,b = 2,c = 3]{}
        if [params[i].type == 'AssignmentPattern'] {
            ret.push[params[i].left.name]
        } else {
            ret.push[params[i].name];
        }
    }

    return ret;
}

It works even with code like this:

getParameters[function [hello /*, foo ],* /bar* { */,world] {}]; // ["hello", "world"]

answered Feb 26, 2014 at 13:39

The proper way to do this is to use a JS parser. Here is an example using acorn.

const acorn = require['acorn'];    

function f[a, b, c] {
   // ...
}

const argNames = acorn.parse[f].body[0].params.map[x => x.name];
console.log[argNames];  // Output: [ 'a', 'b', 'c' ]

The code here finds the names of the three [formal] parameters of the function f. It does so by feeding f into acorn.parse[].

answered Jul 1, 2018 at 22:33

Itay MamanItay Maman

29.6k10 gold badges84 silver badges115 bronze badges

1

I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.

//define like
function test[args] {
    for[var item in args] {
        alert[item];
        alert[args[item]];
    }
}

//then used like
test[{
    name:"Joe",
    age:40,
    admin:bool
}];

answered Jun 17, 2009 at 16:00

hugowarehugoware

34.8k24 gold badges60 silver badges70 bronze badges

2

I don't know if this solution suits your problem, but it lets you redefine whatever function you want, without having to change code that uses it. Existing calls will use positioned params, while the function implementation may use "named params" [a single hash param].

I thought that you will anyway modify existing function definitions so, why not having a factory function that makes just what you want:








var withNamedParams = function[params, lambda] {
    return function[] {
        var named = {};
        var max   = arguments.length;

        for [var i=0; i]|{]/m
const REGEX_PARAMETERS_VALUES = /\s*[\w+]\s*[?:=\s*[[?:[?:[['"]][?:\3|[?:.*?[^\\]\3]]][[\s*\+\s*][?:[?:[['"]][?:\6|[?:.*?[^\\]\6]]]|[?:[\w$]*]]]*]|.*?]]?\s*[?:,|$]/gm

/**
 * Retrieve a function's parameter names and default values
 * Notes:
 *  - parameters with default values will not show up in transpiler code [Babel] because the parameter is removed from the function.
 *  - does NOT support inline arrow functions as default values
 *      to clarify: [ name = "string", add = defaultAddFunction ]   - is ok
 *                  [ name = "string", add = [ a ]=> a + 1 ]        - is NOT ok
 *  - does NOT support default string value that are appended with a non-standard [ word characters or $ ] variable name
 *      to clarify: [ name = "string" + b ]         - is ok
 *                  [ name = "string" + $b ]        - is ok
 *                  [ name = "string" + b + "!" ]   - is ok
 *                  [ name = "string" + λ ]         - is NOT ok
 * @param {function} func
 * @returns {Array} - An array of the given function's parameter [key, default value] pairs.
 */
function getParams[func] {

  let functionAsString = func.toString[]
  let params = []
  let match
  functionAsString = functionAsString.replace[REGEX_COMMENTS, '']
  functionAsString = functionAsString.match[REGEX_FUNCTION_PARAMS][1]
  if [functionAsString.charAt[0] === '['] functionAsString = functionAsString.slice[1, -1]
  while [match = REGEX_PARAMETERS_VALUES.exec[functionAsString]] params.push[[match[1], match[2]]]
  return params

}



// Lets run some tests!

var defaultName = 'some name'

function test1[param1, param2, param3] { return [param1] => param1 + param2 + param3 }
function test2[param1, param2 = 4 * [5 / 3], param3] {}
function test3[param1, param2 = "/root/" + defaultName + ".jpeg", param3] {}
function test4[param1, param2 = [a] => a + 1] {}

console.log[getParams[test1]] 
console.log[getParams[test2]]
console.log[getParams[test3]]
console.log[getParams[test4]]

// [ [ 'param1', undefined ], [ 'param2', undefined ], [ 'param3', undefined ] ]
// [ [ 'param1', undefined ], [ 'param2', '4 * [5 / 3]' ], [ 'param3', undefined ] ]
// [ [ 'param1', undefined ], [ 'param2', '"/root/" + defaultName + ".jpeg"' ], [ 'param3', undefined ] ]
// [ [ 'param1', undefined ], [ 'param2', '[ a' ] ]
// --> This last one fails because of the inlined arrow function!


var arrowTest1 = [a = 1] => a + 4
var arrowTest2 = a => b => a + b
var arrowTest3 = [param1 = "/" + defaultName] => { return param1 + '...' }
var arrowTest4 = [param1 = "/" + defaultName, param2 = 4, param3 = null] => { [] => param3 ? param3 : param2 }

console.log[getParams[arrowTest1]]
console.log[getParams[arrowTest2]]
console.log[getParams[arrowTest3]]
console.log[getParams[arrowTest4]]

// [ [ 'a', '1' ] ]
// [ [ 'a', undefined ] ]
// [ [ 'param1', '"/" + defaultName' ] ]
// [ [ 'param1', '"/" + defaultName' ], [ 'param2', '4' ], [ 'param3', 'null' ] ]


console.log[getParams[[param1] => param1 + 1]]
console.log[getParams[[param1 = 'default'] => { return param1 + '.jpeg' }]]

// [ [ 'param1', undefined ] ]
// [ [ 'param1', '\'default\'' ] ]

As you can tell some of the parameter names disappear because the Babel transpiler removes them from the function. If you would run this in the latest NodeJS it works as expected [The commented results are from NodeJS].

Another note, as stated in the comment is that is does not work with inlined arrow functions as a default value. This simply makes it far to complex to extract the values using a RegExp.

Please let me know if this was useful for you! Would love to hear some feedback!

answered Dec 25, 2016 at 16:16

SnailCrusherSnailCrusher

1,24411 silver badges10 bronze badges

How I typically do it:

function name[arg1, arg2]{
    var args = arguments; // array: [arg1, arg2]
    var objecArgOne = args[0].one;
}
name[{one: "1", two: "2"}, "string"];

You can even ref the args by the functions name like:

name.arguments;

Hope this helps!

answered Aug 20, 2012 at 1:17

CodyCody

9,4394 gold badges59 silver badges45 bronze badges

2

I'll give you a short example below:

function test[arg1,arg2]{
    var funcStr = test.toString[]
    var leftIndex = funcStr.indexOf['['];
    var rightIndex = funcStr.indexOf[']'];
    var paramStr = funcStr.substr[leftIndex+1,rightIndex-leftIndex-1];
    var params = paramStr.split[','];
    for[param of params]{
        console.log[param];   // arg1,arg2
    }
}

test[];

answered May 19, 2017 at 7:29

2

This package uses recast in order to create an AST and then the parameter names are gathered from their, this allows it to support pattern matching, default arguments, arrow functions and other ES6 features.

//www.npmjs.com/package/es-arguments

answered Oct 14, 2017 at 17:31

I have modified the version taken from AngularJS that implements a dependency injection mechanism to work without Angular. I have also updated the STRIP_COMMENTS regex to work with ECMA6, so it supports things like default values in the signature.

var FN_ARGS = /^function\s*[^\[]*\[\s*[[^\]]*]\]/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*[_?][.+?]\1\s*$/;
var STRIP_COMMENTS = /[\/\/.*$]|[\/\*[\s\S]*?\*\/]|[\s*=[^,\]]*[['[?:\\'|[^'\r\n]]*']|["[?:\\"|[^"\r\n]]*"]]|[\s*=[^,\]]*]]/mg;

function annotate[fn] {
  var $inject,
    fnText,
    argDecl,
    last;

  if [typeof fn == 'function'] {
    if [![$inject = fn.$inject]] {
      $inject = [];
      fnText = fn.toString[].replace[STRIP_COMMENTS, ''];
      argDecl = fnText.match[FN_ARGS];
      argDecl[1].split[FN_ARG_SPLIT].forEach[function[arg] {
        arg.replace[FN_ARG, function[all, underscore, name] {
          $inject.push[name];
        }];
      }];
      fn.$inject = $inject;
    }
  } else {
    throw Error["not a function"]
  }
  return $inject;
}

console.log["function[a, b]",annotate[function[a, b] {
  console.log[a, b, c, d]
}]]
console.log["function[a, b = 0, /*c,*/ d]",annotate[function[a, b = 0, /*c,*/ d] {
  console.log[a, b, c, d]
}]]
annotate[{}]

answered Nov 29, 2017 at 23:28

loretoparisiloretoparisi

14.8k11 gold badges93 silver badges132 bronze badges

You can access the argument values passed to a function using the "arguments" property.

    function doSomething[]
    {
        var args = doSomething.arguments;
        var numArgs = args.length;
        for[var i = 0 ; i < numArgs ; i++]
        {
            console.log["arg " + [i+1] + " = " + args[i]];  
                    //console.log works with firefox + firebug
                    // you can use an alert to check in other browsers
        }
    }

    doSomething[1, '2', {A:2}, [1,2,3]];    

answered Jun 17, 2009 at 18:11

letronjeletronje

8,8119 gold badges43 silver badges53 bronze badges

2

It's pretty easy.

At the first there is a deprecated arguments.callee — a reference to called function. At the second if you have a reference to your function you can easily get their textual representation. At the third if you calling your function as constructor you can also have a link via yourObject.constructor. NB: The first solution deprecated so if you can't to not use it you must also think about your app architecture. If you don't need exact variable names just use inside a function internal variable arguments without any magic.

//developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee

All of them going to call toString and replace with re so we can create a helper:

// getting names of declared parameters
var getFunctionParams = function [func] {
    return String[func].replace[/[^\[]+\[[[^\]]*]\].*/m, '$1'];
}

Some examples:

// Solution 1. deprecated! don't use it!
var myPrivateFunction = function SomeFuncName [foo, bar, buz] {
    console.log[getFunctionParams[arguments.callee]];
};
myPrivateFunction [1, 2];

// Solution 2.
var myFunction = function someFunc [foo, bar, buz] {
    // some code
};
var params = getFunctionParams[myFunction];
console.log[params];

// Solution 3.
var cls = function SuperKewlClass [foo, bar, buz] {
    // some code
};
var inst = new cls[];
var params = getFunctionParams[inst.constructor];
console.log[params];

Enjoy with JS!

UPD: Jack Allan was provided a little bit better solution actually. GJ Jack!

answered Feb 1, 2013 at 23:30

1

Whatever the solution, it must not break on wierd functions, whose toString[] looks just as wierd:

function  [  A,  b
,c      ,d
]{}

Also, why use complex regular expressions? This can be done like:

function getArguments[f] {
    return f.toString[].split[']',1][0].replace[/\s/g,''].substr[9].split[','];
}

This works everywhere with every function, and the only regex is whitespace removal that doesn't even process the whole string due to the .split trick.

answered May 19, 2015 at 10:02

Camilo MartinCamilo Martin

36.3k20 gold badges109 silver badges153 bronze badges

Ok so an old question with plenty of adequate answers. here is my offering that does not use regex, except for the menial task of stripping whitespace . [I should note that the "strips_comments" function actually spaces them out, rather than physically remove them. that's because i use it elsewhere and for various reasons need the locations of the original non comment tokens to stay intact]

It's a fairly lengthy block of code as this pasting includes a mini test framework.

    function do_tests[func] {

    if [typeof func !== 'function'] return true;
    switch [typeof func.tests] {
        case 'undefined' : return true;
        case 'object'    : 
            for [var k in func.tests] {

                var test = func.tests[k];
                if [typeof test==='function'] {
                    var result = test[func];
                    if [result===false] {
                        console.log[test.name,'for',func.name,'failed'];
                        return false;
                    }
                }

            }
            return true;
        case 'function'  : 
            return func.tests[func];
    }
    return true;
} 
function strip_comments[src] {

    var spaces=[s]=>{
        switch [s] {
            case 0 : return '';
            case 1 : return ' ';
            case 2 : return '  ';
        default : 
            return Array[s+1].join[' '];
        }
    };

    var c1 = src.indexOf ['/*'],
        c2 = src.indexOf ['//'],
        eol;

    var out = "";

    var killc2 = [] => {
                out += src.substr[0,c2];
                eol =  src.indexOf['\n',c2];
                if [eol>=0] {
                    src = spaces[eol-c2]+'\n'+src.substr[eol+1];
                } else {
                    src = spaces[src.length-c2];
                    return true;
                }

             return false;
         };

    while [[c1>=0] || [c2>=0]] {
         if [c1>=0] {
             // c1 is a hit
             if [ [c1=0] {
                     // c2 is a hit and it beats c1
                     if [killc2[]] break;
                 }
             }
         } else {
             if [c2>=0] {
                // c2 is a hit, c1 is a miss.
                if [killc2[]] break;  
             } else {
                 // both c1 & c2 are a miss
                 break;
             }
         }

         c1 = src.indexOf ['/*'];
         c2 = src.indexOf ['//'];   
        }

    return out + src;
}

function function_args[fn] {
    var src = strip_comments[fn.toString[]];
    var names=src.split[']'][0].replace[/\s/g,''].split['['][1].split[','];
    return names;
}

function_args.tests = [

     function test1 [] {

            function/*al programmers will sometimes*/strip_comments_tester/* because some comments are annoying*/[
            /*see this---[[[*/ src//]] it's an annoying comment does not help anyone understand if the 
            ,code,//really does
            /**/sucks ,much /*?*/]/*who would put "comment\" about a function like [this] { comment } here?*/{

            }


        var data = function_args[strip_comments_tester];

        return [ [data.length==4] &&
                 [data[0]=='src'] &&
                 [data[1]=='code'] &&
                 [data[2]=='sucks'] &&
                 [data[3]=='much']  ];

    }

];
do_tests[function_args];

answered Aug 3, 2016 at 10:35

unsynchronizedunsynchronized

4,7692 gold badges30 silver badges41 bronze badges

Here's one way:

// Utility function to extract arg name-value pairs
function getArgs[args] {
    var argsObj = {};

    var argList = /\[[[^]]*]/.exec[args.callee][1];
    var argCnt = 0;
    var tokens;
    var argRe = /\s*[[^,]+]/g;

    while [tokens = argRe.exec[argList]] {
        argsObj[tokens[1]] = args[argCnt++];
    }

    return argsObj;
}

// Test subject
function add[number1, number2] {
    var args = getArgs[arguments];
    console.log[args]; // [{ number1: 3, number2: 4 }]
}

// Invoke test subject
add[3, 4];

Note: This only works on browsers that support arguments.callee.

answered Jun 17, 2009 at 19:14

Ates GoralAtes Goral

134k26 gold badges135 silver badges189 bronze badges

5

Note: if you want to use ES6 parameter destructuring with the top solution add the following line.

if [result[0] === '{' && result[result.length - 1 === '}']] result = result.slice[1, -1]

answered Jan 5, 2018 at 22:47

Chủ Đề