简体   繁体   English

JavaScript调用名称为匿名作用域中的函数的字符串形式的函数

[英]JavaScript call a function who's name is a in string for a function in a anonymous scope

Is this doable in javascript ? 这在javascript中可行吗? I try to call the function who's name is in the variable named "name" (sorry!). 我试着调用名为“name”的变量的函数(对不起!)。 That function is not in the global scope. 该功能不在全球范围内。

(function () {
    var myFunc, name;

    myFunc = function(){
        alert("Hi!");
    };
    name = "myFunc";
    //myFunc();  // work

    (name)();   // do not work
    this[name]();   // do not work

})();

Note: I have a jsfiddle entry here 注意:我在这里有一个jsfiddle条目

There is not an object for the "local scope" like there is for the global scope. “本地范围”没有对象,就像全局范围一样。 You can (and should) make your own object to hold your functions: 您可以(并且应该)创建自己的对象来保存您的功能:

(function () {
    var name = "myFunc";

    var funcs = {
        myFunc: function(){
            alert("Hi!");
        }
    };

    funcs[name]();
})();
eval(name)();

eval is not always evil. eval并不总是邪恶的。 It does have its uses. 它确实有它的用途。

If you really don't like eval, try storing your variables in an object instead: 如果您真的不喜欢评估,请尝试将变量存储在对象中:

(function () {
    var vars = {};

    vars.myFunc = function(){
        alert("Hi!");
    };

    vars.name = "myFunc";
    //vars.myFunc();  // work

    vars[vars.name]();    
})();

Change 更改

myFunc = function(){

to

this.myFunc = function(){

then this will work: 然后这将工作:

this[name]();

Demo: http://jsfiddle.net/B7QVj/6/ 演示: http//jsfiddle.net/B7QVj/6/

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

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