3

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.

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.

3
  • You have to use eval() to turn the string into an object, otherwise it's just a string. But beware the security issues around the use of eval() Commented May 17, 2011 at 14:26
  • 1
    I think you want o[funcName](data). Commented May 17, 2011 at 14:28
  • possible duplicate of How to execute a JavaScript function when I have its name as a string Commented Apr 25, 2012 at 1:21

2 Answers 2

4

Assuming it is a global function:

window['foo']()

is the same as to

foo()
Sign up to request clarification or add additional context in comments.

2 Comments

It's not a global function. It's on an object hanging off a DIV. See o = $(divId).data('myObject') above.
In that case: the_div['foo']()
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.