gpt4 book ai didi

Javascript:在没有 eval 的情况下使用函数名称从 String 调用用匿名函数编写的函数?

转载 作者:行者123 更新时间:2023-11-29 10:00:16 25 4
gpt4 key购买 nike

更新2:
我真正想问的问题已经在不同的页面上争论过了。请检查以下条目。
(感谢 BobS。)
How can I access local scope dynamically in javascript?


你好。

我已经开始使用 jQuery 并且想知道如何从 String 动态调用匿名函数中的函数。比方说,我有以下功能:

function foo() {
// Being in the global namespace,
// this function can be called with window['foo']()
alert("foo");
}

jQuery(document).ready(function(){
function bar() {
// How can this function be called
// by using a String of the function's name 'bar'??
alert("bar");
}

// I want to call the function bar here from String with the name 'bar'
}

我一直在试图弄清楚什么是“window”的对应物,它可以调用全局命名空间中的函数,例如 window["foo"]。在上面的小例子中,如何从字符串“bar”中调用函数 bar?

感谢您的帮助。

更新:
这是我想要的:

  1. 定义仅在闭包中使用的函数。
  2. 避免在包含这些函数的闭包中创建对象,以便作为 obj['bar'] 访问。
  3. 避免 eval(如果可能)以便以更直接的方式更简单地编写代码(如果存在)。
  4. 通过 URI 参数或任何变量动态决定函数的名称。

作为 Javascript 的新手,我认为 'this' 将是闭包中 'window' 的对应物,并尝试编写:

// in the closure
name = 'bar';
this[name]; // undefined ...

失败了(当然...)。
这一切都是为了追求更进一步的懒惰。 Javascript 对我来说有点陌生,目前我一直在尝试尽可能偷懒地编写代码。

最佳答案

正如 Kobi 所写,eval 可能是一个不错的选择。或者,是否有任何理由不这样做

$(function(){
var localNamespace = {};
function bar() {
alert("bar");
}
localNamespace['bar'] = bar;
// Now bar() can be called by, well, localNamespace['bar']
}

更新:类似的 SO 条目,例如 How can I access local scope dynamically in javascript? , 似乎表明如果不使用这两种方法中的一种或更丑陋的方法,你就不走运了。

关于Javascript:在没有 eval 的情况下使用函数名称从 String 调用用匿名函数编写的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2399422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com