使用字符串调用JavaScript函数名称?

Dio*_*ane 47 javascript

如何将事件连接到我定义为字符串的函数名称?

我正在使用Prototype.js,虽然这不是Prototype-speficic.

$(inputId).observe('click', formData.fields[x].onclick);
Run Code Online (Sandbox Code Playgroud)

这会导致JavaScript抱怨我的处理程序不是函数.我不希望我们使用eval().

Gre*_*reg 81

如果函数在全局范围内,则可以使用window对象获取它:

var myFunc = window[myFuncName];
Run Code Online (Sandbox Code Playgroud)

  • ...或范围[myFuncName]一般 (11认同)

Iko*_*kon 9

我已经解决了这个问题,因为我需要这样的功能.这是我的沙箱代码,没有经过全面测试,但可以成为其他人的起点.请注意,代码中有一个eval(),因为我无法弄清楚如何绕过该步骤,可能是一个javascript怪癖,无法以任何其他方式完成.如果有办法摆脱eval(),请告诉我!

executeFunctionByName = function(functionName)
{
    var args = Array.prototype.slice.call(arguments).splice(1);
    //debug
    console.log('args:', args);

    var namespaces = functionName.split(".");
    //debug
    console.log('namespaces:', namespaces);

    var func = namespaces.pop();
    //debug
    console.log('func:', func);

    ns = namespaces.join('.');
    //debug
    console.log('namespace:', ns);

    if(ns == '')
    {
        ns = 'window';
    }

    ns = eval(ns);
    //debug
    console.log('evaled namespace:', ns);

    return ns[func].apply(ns, args);
}


core = {
    paragraph: {
        titlebar: {
            user: "ddd",
            getUser: function(name)
            {
                this.user = name;
                return this.user;
            }
        }
    }
}

var testf = function()
{
    alert('dkdkdkd');
}

var x = executeFunctionByName('core.paragraph.titlebar.getUser', 'Ikon');
executeFunctionByName('testf');
Run Code Online (Sandbox Code Playgroud)


dkr*_*etz 6

......或者这个[myFuncName];


Ant*_*ife 5

也许?

setTimeout ( "myFunc()", 1 );
Run Code Online (Sandbox Code Playgroud)


小智 5

只需一个eval即可完成工作

var call = eval("method_name").call(args);
Run Code Online (Sandbox Code Playgroud)