I want to write a function in JavaScript, it needs to get the string form (text in source code) of its parameter instead of the value of the parameter.
Note: The type of the parameter may be anything, not restricted to be of string, and the value of the parameter may be any expression.
For example:
function processParam(param)
{
let literalCode = "";
...
}
// I want to get the string "100 * 2" instead of 200 inside this function.
processParam(100 * 2);
// I want to get the string "console.log('abc')" instead of undefined inside this function.
processParam(console.log('abc'));
In other words, I want to get the code of the line that is currently running. How can I do this?
That is not really possible like that. But with a slight change you can get some source code. Functions have source code. So if you pass the argument as a function, you can get the source code. And if you want the actual value, you should execute it.
Here is a demo:
function processParam(param){
let literalCode = param.toString().split("=>").pop().trim();
console.log(literalCode);
let actualValue = param(); // execute it
}
processParam(() =>100 * 2);
processParam(() => console.log('abc'));