简体   繁体   中英

How can I call an anonymous function (stored in string) with an argument in JavaScript?

I have the following situation in JavaScript:

<a onclick="handleClick(this, {onSuccess : 'function() { alert(\'test\') }'});">Click</a>

The handleClick function receives the second argument as a object with a onSuccess property containing the function definition...

How do I call the onSuccess function (which is stored as string) -and- pass otherObject to that function? (jQuery solution also fine...)?

This is what I've tried so far...

function handleClick(element, options, otherObject) {
    options.onSuccess = 'function() {alert(\'test\')}';

    options.onSuccess(otherObject); //DOES NOT WORK
    eval(options.onSuccess)(otherObject); //DOES NOT WORK
}

You really don't need to do this. Pass the function around as a string, i mean. JavaScript functions are first-class objects, and can be passed around directly:

<a onclick="handleClick(this, {onSuccess : function(obj) { alert(obj) }}, 'test');">
  Click
</a>

...

function handleClick(element, options, otherObject) {
    options.onSuccess(otherObject); // works...
}

But if you really want to do it your way, then cloudhead's solution will do just fine.

Try this:

 options.onSuccess = eval('function() {alert(\'test\')}');
 options.onSuccess(otherObject);

It only worked on my FF when I added an assignmnet into a dummy variable:

 options.onSuccess = 'dummyVariable = function(x) {alert("x=" + x);}';
 f = eval(options.onSuccess);
 f(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM