[英]How to get the code of the line currently running in JavaScript?
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.我想在JavaScript中写一个function,它需要获取其参数的字符串形式(源代码中的文本)而不是参数的值。
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.
因此,如果您将参数作为 function 传递,您可以获得源代码。 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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.