如何获得当前在JavaScript中运行的行代码?



我想在JavaScript中编写一个函数,它需要获得其参数的字符串形式(源代码中的文本),而不是参数的值。

注意:形参的类型可以是任何类型,不限于字符串,形参的值可以是任何表达式。

例如:

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')); 

换句话说,我想获得当前正在运行的行代码。我该怎么做呢?

这是不可能的。但是只要稍微更改一下你可以得到一些源代码。函数有源代码。如果你通过参数作为一个函数,你可以得到源代码。如果你想要实际的值,你应该执行它。

下面是一个示例:

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'));

相关内容

最新更新