Author: YunFeng Githubgithub.com/ihtml5
The problem
How do I get a function parameter? We all know that arguments can be used to get the value of a run-time argument, but how to get the value of a parameter
toString
Function. The prototype. There’s a phrase in the toString, said in a Function call the toString method directly, will return to the source code of this Function as a string. The important message here is how powerful and simple it is to decompile and parse the source of a function by calling toString().
/ / lu code
function tq(a, b, c) {}
tq.toString();
// "function tq(a, b, c) {}
Copy the code
Several methods to get function parameters have been written by predecessors
- Get-parameter-names is recommended
//https://github.com/goatslacker/get-parameter-names/blob/master/index.js
// If you can't read the re, go to https://regexper.com
var COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*? \*\/))/mg;
var DEFAULT_PARAMS = /=[^,]+/mg;
var FAT_ARROWS = /=>.*$/mg;
function getParameterNames(fn) {
var code = fn.toString()
.replace(COMMENTS, ' ')
.replace(FAT_ARROWS, ' ')
.replace(DEFAULT_PARAMS, ' ');
var result = code.slice(code.indexOf('(') + 1, code.indexOf(') '))
.match(/([^\s,]+)/g);
return result === null
? []
: result;
}
module.exports = getParameterNames;
Copy the code
- It’s similar to 1
function getArgs(func) {
// Get the string that matches the parameter pattern with the re.
// The first grouping is this: ([^)]*) any character that is not a close parenthesis
var args = func.toString().match(/function\s.*? \ \ (((^)] *)) /) [1];
// Use commas to separate arguments (arguments string).
return args.split(",").map(function(arg) {
// Remove comments (inline comments) and Spaces
return arg.replace(/ / \ \ *. *, *, / /."").trim();
}).filter(function(arg) {
// Make sure there is no undefined.
return arg;
});
}
Copy the code
- Zhihu shi Jun he offers a simpler approach
//https://www.zhihu.com/question/28912825/\(\s*([\s\S]*?) \s*\)/.exec(fn)[1].split(/\s*,\s*/)
Copy the code
Method 1 takes into account single-line comments, multi-line comments, default values, arrow functions, and more adaptability. Method 1 is recommended
ToString Other uses
- Object.prototype.toString
Determine the type of a variable. This is often used in libraries such as jquery
Object.prototype.toString.call(obj);
Copy the code
- Number.prototype.toString
Converting numbers to strings, such as 1 to ‘1’
- Boolean.prototype.toString
var b = true;
console.log(b.toString()); // 'true'
Copy the code
- Array.prototype.toString
[].join(‘,’);
[].toString() / /"
[1.2].toString() / / '1, 2,'
Copy the code
- Symbol.prototype.toString
Behavior is similar to the Function. The prototype. Will the toString Symbol Function source code parsing