使用JavaScript反射调用功能

发布于 2025-01-27 04:37:10 字数 182 浏览 3 评论 0原文

我是JavaScript的新手,并且正在为Reflection在那里的工作方式挣扎。 我要做的是:给定一个函数名称的字符串,调用该函数。 例如,给出了var mystring =“ myFunctionName()”,然后我想以某种方式使用mystring调用myFunctionName()。

这是可能的吗?

提前致谢!

I am new to JavaScript and am struggling with how reflection works there.
What I want to do is: Given a String which is the function's name, invoke that function.
E.g. var myString = "myFunctionName()" is given and then I want to invoke myFunctionName() using myString somehow.

Is this possible and how?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晌融 2025-02-03 04:37:10

这完全取决于声明函数的上下文。

对于浏览器的窗口上下文:

function test() {
  console.log('Hello world!');
}

const string = 'test';

window[string]();

It all depends on the context in which the function is declared.

For the browser's window context:

function test() {
  console.log('Hello world!');
}

const string = 'test';

window[string]();

没企图 2025-02-03 04:37:10

您可以尝试:

function myFunctionName() {
  // do something...
}

var myString = "myFunctionName()";

eval(myString) 

You can try:

function myFunctionName() {
  // do something...
}

var myString = "myFunctionName()";

eval(myString) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文