不使用eval调用函数?

时间:2022-08-24 14:56:21

I have an object attached as data to a DIV. I also have a string that contains the name of a function of that object.

我有一个对象作为数据附加到DIV。我还有一个字符串,其中包含该对象的函数名称。

function callFunction(divId, funcName, data) {
  o = $(divId).data('myObject');
  // how do I call o.funcName(data) ???

// Somewhere else...
callFunction('#myDivId', "myFunction", someData);

The divId and funcName are actually coming from a Java applet on the page, which is why they're strings.

divId和funcName实际上来自页面上的Java applet,这就是为什么它们是字符串。

2 个解决方案

#1


4  

Assuming it is a global function:

假设它是一个全局函数:

window['foo']()

is the same as to

是一样的

foo()

#2


1  

Depends on your functions scope. It it's attached to the window, you can do this;

取决于您的功能范围。它附在窗户上,你可以这样做;

<script>
    var my_dynamic_function = function(param) {
        alert(param);
    };

    var callFunction = function(divId, funcName, data) {
        ...
        window[funcName]('PARAM!');
    };

    ...

    callFunction('#myDivId', 'my_dynamic_function', data);
</script>

#1


4  

Assuming it is a global function:

假设它是一个全局函数:

window['foo']()

is the same as to

是一样的

foo()

#2


1  

Depends on your functions scope. It it's attached to the window, you can do this;

取决于您的功能范围。它附在窗户上,你可以这样做;

<script>
    var my_dynamic_function = function(param) {
        alert(param);
    };

    var callFunction = function(divId, funcName, data) {
        ...
        window[funcName]('PARAM!');
    };

    ...

    callFunction('#myDivId', 'my_dynamic_function', data);
</script>