简体   繁体   English

如何获取JavaScript当前运行的线路代码?

[英]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.

相关问题 如何使用Javascript获取当前运行脚本的路径? - How do I get the path of the currently running script with Javascript? 如何中断当前运行的JavaScript - How to break on currently running JavaScript 如何获取当前正在执行的javascript代码的文件路径 - How to get the file-path of the currently executing javascript code 如何查看当前正在执行的javascript代码? - how to see what javascript code is currently executing? 我可以在 JavaScript 中获取当前正在运行的函数的名称吗? - Can I get the name of the currently running function in JavaScript? javascript如何获取当前不可见的元素 - javascript how to get element that is currently not visible 当前正在运行的javascript函数名称? - Currently running javascript function name? 如何使用jquery或javascript知道当前在元素上运行的动画 - How to know that which animation is currently running on an element using jquery or javascript 如何在Office for Office 2013中获取当前正在运行的应用程序的名称 - How to get the name of currently running app in an App for office 2013 如何通过JavaScript获取<select>中当前选择的<option>? - How do you get the currently selected <option> in a <select> via JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM