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

时间:2022-02-28 16:58:06

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.

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

$(inputId).observe('click', formData.fields[x].onclick);

This would result in JavaScript complaining that my handler is not a function. I would prefer not us use eval().

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

10 个解决方案

#1


79  

If the function is in the global scope, you can get it using the window object:

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

var myFunc = window[myFuncName];

#2


9  

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!

我已经解决了这个问题,因为我需要这样的功能。这是我的沙盒代码,未经过全面测试,但可以作为其他人的起点。请注意,代码中有一个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');

#3


6  

... or this[myFuncName];

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

#4


5  

Perhaps?

也许?

setTimeout ( "myFunc()", 1 );

#5


3  

Looks like formData.fields[x].onclick holds the name of a global function? If so try:

看起来像formData.fields [x] .onclick包含全局函数的名称?如果是这样尝试:

$(inputId).observe('click', window[formData.fields[x].onclick]);

#6


3  

window.myFunction === window["myFunction"]

#7


3  

Just an eval would do the job

只需一个评估就可以完成这项工作

var call = eval("method_name").call(args);

#8


1  

Do you know what the onclick property contains or what type it is? I assume this is prototype specific stuff, as "fields" does not exist in DOM forms.

你知道onclick属性包含什么或者它是什么类型的?我认为这是原型特定的东西,因为DOM形式中不存在“字段”。

#9


0  

If you need to call a string function with arguments, do this:

如果需要使用参数调用字符串函数,请执行以下操作:

window[stringFunctionName].apply( window, arrayOfArguments )

You can use scope in place of window if preferred

如果愿意,您可以使用范围代替窗口

#10


0  

update:--- use ES6 export and import

更新:---使用ES6导出和导入

a.js

a.js

const fn = {
  aaa: function() {
    //code
  },
  bbb: function() {
    //code
  },
  //codes ....
  nnn: function() {
    //code
  }
}

export default fn

b.js

b.js

  import someFn from './a'
  //eg
  const str1='aaa'
  const str2 = 'bbb'

  someFn[str1]()

  • eval('str') (obsolete feature https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features )

    eval('str')(过时的功能https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features)

  • setTimeout('str') setInterval('str')

    setTimeout('str')setInterval('str')

  • window['str'] (but...sometimes,global object is not window)

    window ['str'](但......有时,全局对象不是窗口)

  • new Function('str')

    新功能('str')

These methods above always not be recommend by some reasons, but they are really convenient to use. These methods below are safe, but really not conveninet to use.

上面的这些方法总是由于某些原因而不推荐,但它们使用起来非常方便。下面这些方法是安全的,但实际上并不便于使用。

  • switch...case (or if...else)

    切换...案例(或者如果......其他)

    switch(str){
        case 'str1': 
            fn1()
            break
        case 'str2':
            fn2
            //and so on
    }
    
  • put functions in a object

    将函数放在一个对象中

    const fn={
        str1:fn1,
        str2:fn2
        //and so on
    }
    fn[str1] //call function
    

#1


79  

If the function is in the global scope, you can get it using the window object:

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

var myFunc = window[myFuncName];

#2


9  

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!

我已经解决了这个问题,因为我需要这样的功能。这是我的沙盒代码,未经过全面测试,但可以作为其他人的起点。请注意,代码中有一个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');

#3


6  

... or this[myFuncName];

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

#4


5  

Perhaps?

也许?

setTimeout ( "myFunc()", 1 );

#5


3  

Looks like formData.fields[x].onclick holds the name of a global function? If so try:

看起来像formData.fields [x] .onclick包含全局函数的名称?如果是这样尝试:

$(inputId).observe('click', window[formData.fields[x].onclick]);

#6


3  

window.myFunction === window["myFunction"]

#7


3  

Just an eval would do the job

只需一个评估就可以完成这项工作

var call = eval("method_name").call(args);

#8


1  

Do you know what the onclick property contains or what type it is? I assume this is prototype specific stuff, as "fields" does not exist in DOM forms.

你知道onclick属性包含什么或者它是什么类型的?我认为这是原型特定的东西,因为DOM形式中不存在“字段”。

#9


0  

If you need to call a string function with arguments, do this:

如果需要使用参数调用字符串函数,请执行以下操作:

window[stringFunctionName].apply( window, arrayOfArguments )

You can use scope in place of window if preferred

如果愿意,您可以使用范围代替窗口

#10


0  

update:--- use ES6 export and import

更新:---使用ES6导出和导入

a.js

a.js

const fn = {
  aaa: function() {
    //code
  },
  bbb: function() {
    //code
  },
  //codes ....
  nnn: function() {
    //code
  }
}

export default fn

b.js

b.js

  import someFn from './a'
  //eg
  const str1='aaa'
  const str2 = 'bbb'

  someFn[str1]()

  • eval('str') (obsolete feature https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features )

    eval('str')(过时的功能https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features)

  • setTimeout('str') setInterval('str')

    setTimeout('str')setInterval('str')

  • window['str'] (but...sometimes,global object is not window)

    window ['str'](但......有时,全局对象不是窗口)

  • new Function('str')

    新功能('str')

These methods above always not be recommend by some reasons, but they are really convenient to use. These methods below are safe, but really not conveninet to use.

上面的这些方法总是由于某些原因而不推荐,但它们使用起来非常方便。下面这些方法是安全的,但实际上并不便于使用。

  • switch...case (or if...else)

    切换...案例(或者如果......其他)

    switch(str){
        case 'str1': 
            fn1()
            break
        case 'str2':
            fn2
            //and so on
    }
    
  • put functions in a object

    将函数放在一个对象中

    const fn={
        str1:fn1,
        str2:fn2
        //and so on
    }
    fn[str1] //call function