Call a JavaScript function name using a string?

前端 未结 10 1056
孤独总比滥情好
孤独总比滥情好 2020-11-30 07:07

How can I hook up an event to a function name I have defined as a string?

I\'m using Prototype.js, although this is not Prototype-speficic.

$(inputId         


        
10条回答
  •  有刺的猬
    2020-11-30 07:42

    I have worked on this problem, as I needed a function like this. Here is my sandbox code, not thoroughly tested, but can be a startpoint for others. Note that there is one eval() in the code as I couldn't figure out how to bypass that step, maybe a javascript quirk and cannot be done in any other way. Let me know if there is a way to get rid of eval() here!

    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: "ffffd",
                getUser: function(name)
                {
                    this.user = name;
                    return this.user;
                }
            }
        }
    }
    
    var testf = function()
    {
        alert('dkdkdkd');
    }
    
    var x = executeFunctionByName('core.paragraph.titlebar.getUser', 'Ikon');
    executeFunctionByName('testf');
    

提交回复
热议问题