问题描述
function foo(x = 5){
//我不控制的东西
}
有没有办法获得这里的默认值 x
最佳的方式是:
getDefaultValues(foo); // {x:5}
请注意, toString
该函数将无法正常工作,因为它将在不是常量的默认值上中断。
由于我们在JS中没有经典反思,因为您可以在C#,Ruby等上找到依靠我最喜欢的工具,正则表达式,为我们做这个工作:
let b =foo;
函数fn(x = 10,/ * woah * / y = 20,z,a = b){/ * ... * /}
fn.toString()
.match(/ ^ function\s * [^ \(] * \(\s *([^ \)] *)\)/ m)[1] //获取参数声明括号
.replace(/(\ / \ * [\s\S] *?\ * \ /)/ mg,'')//摆脱评论
.split(',')
.reduce(function(parameters,param){//将其转换为对象
param = param.match(/([_ $ a-zA-Z] [^ =] *)(?:=([^ =] +))?/); //从值
参数分割参数名称[param [1] .trim()] = eval(param [2 ]); //评估每个默认值,获取字符串,变量refs等。
返回参数;
},{});
//对象{x:10,y:20,z:undefined,a:foo}
如果您要使用此功能,只需确保正在缓存正则表现形式。
感谢在前两个正则表达式上的提示
Is there a way to retrieve a function's default argument value in JavaScript?
function foo(x = 5) {
// things I do not control
}
Is there a way to get the default value of x
here? Optimally, something like:
getDefaultValues(foo); // {"x": 5}
Note that toString
ing the function would not work as it would break on defaults that are not constant.
Since we don't have classic reflection in JS, as you can find on C#, Ruby, etc., we have to rely on one of my favorite tools, regular expressions, to do this job for us:
let b = "foo";
function fn (x = 10, /* woah */ y = 20, z, a = b) { /* ... */ }
fn.toString()
.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // Get the parameters declaration between the parenthesis
.replace(/(\/\*[\s\S]*?\*\/)/mg,'') // Get rid of comments
.split(',')
.reduce(function (parameters, param) { // Convert it into an object
param = param.match(/([_$a-zA-Z][^=]*)(?:=([^=]+))?/); // Split parameter name from value
parameters[param[1].trim()] = eval(param[2]); // Eval each default value, to get strings, variable refs, etc.
return parameters;
}, {});
// Object { x: 10, y: 20, z: undefined, a: "foo" }
If you're going to use this, just make sure you're caching the regexs for performance.
Thanks to bubersson for hints on the first two regexs
这篇关于获取函数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!