如何根据传递的参数在JavaScript函数中命名匿名函数?

发布于 2025-01-30 19:15:47 字数 285 浏览 3 评论 0原文

我想根据传递的参数给出我函数中的匿名函数的名称。例如,如果传递的参数是“自然”,那么我想创建一个名称的匿名函数。

示例代码:

function hello(nature) {
    window.nature /* I want this word "nature" to be taken from the parameter passed by the function */ = function () {
        console.log('succes');
    }
}

I want to give the anonymous function's name that is inside my function based on the parameters passed. For example, if the passed parameter is "nature" then I want to create an anonymous function with that name.

Example code:

function hello(nature) {
    window.nature /* I want this word "nature" to be taken from the parameter passed by the function */ = function () {
        console.log('succes');
    }
}

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

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

发布评论

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

评论(2

玩物 2025-02-06 19:15:47

您可以通过将字符串作为参数进行操作。
在这里,如何分配自定义名称和自定义功能(如果需要)。

function hello(name, func) {
  window[name] = func;
}

hello('azerty', () => console.log('hello'));
window.azerty() // output 'hello'

You can do it by passing a string as parameter.
Here how to assign a custom name and a custom function, if needed.

function hello(name, func) {
  window[name] = func;
}

hello('azerty', () => console.log('hello'));
window.azerty() // output 'hello'

捶死心动 2025-02-06 19:15:47

这是一个典范,可变“自然”具有值“ fn”,并且传递给“ FN”的参数已记录到控制台。

function hello(method) {
  window[method] = function (param) {
    console.log(param);
  };
}

hello('fn');
window.fn('success');

Here is an exemple where variable "nature" has value "fn" and parameter passed to "fn" is logged to the console.

function hello(method) {
  window[method] = function (param) {
    console.log(param);
  };
}

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