简体   繁体   English

JavaScript中是否可以使用字符串格式的名称来调用在另一个函数范围内声明的函数?

[英]Is there any way in JavaScript to call a function declared inside the scope of another function by using its name available in string format?

Please tell if the below would be possible without making function fun a method of an object. 请说明在不使function fun成为对象方法的情况下是否可以进行以下操作。

(function a() {
var fun = function() {
console.log('abc');
}
var x = 'fun';
// call fun using x (How ?)
})();

You could use eval . 您可以使用eval This will evaluate the string as JavaScript code. 这会将字符串评估为JavaScript代码。

 (function a() { var fun = function() { console.log('abc'); } var x = 'fun'; eval(x)(); })(); 

I always prefer to use window variable to execute my function instead of using eval, also I remember that some browsers throws warnings when you use eval. 我总是更喜欢使用window变量而不是eval来执行我的函数,我还记得一些浏览器在使用eval时会发出警告。 Also at chrome extensions is not enabled by default. 同样在chrome扩展中,默认情况下未启用。

So in my case, you can set a function into windows global variable like this: 因此,就我而言,您可以将函数设置为Windows全局变量,如下所示:

windows.x = function(){
    // do something here
}

and then execute it like this: 然后像这样执行它:

windows["x"]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM