0

please help I have a simple example here

<script type="text/javascript" language="javascript">
    function test(callback1) {
        callback1();
    }
    var f1 = function () {
        alert(1);
    }
</script>

Currently, parameter of the test function is a function, when abc button is clicked, test function will be called and then test will call f1. Everything okie with me.

However, I'd like a small change like this: parameter of the test function will be a string, I mean it should be a function name, test('f1') instead of test(f1). Is it possible?How can I implement this?

Thanks

1

4 Answers 4

2

window[callback1]();

Depending on use I would prefer prepare separate functions map.

var funcMap = {
   f1: function() {...},
   ...
};
funcMap['f4'] = function() {...};
function test(callback1) {
    funcMap[callback1]();
}

It definitely doesn't bloat window namespace and is more secure (window has more methods provided by browser).

Don't use eval - it's evil!

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

Comments

2

eval() is unneeded here. To pass a callback, just pass the function name. Functions are variables.

For example:

function test(a){
    alert(a);
}

function callback(b,a){
    b(a);
}

callback(test, 'dog'); //alerts 'dog'

So, in your code, test(f1) will work fine.

Comments

0

You can use eval() to execute the function which is passed as a string. But its deprecated to use eval.

Example:

function test(someFunctionName) {
        eval(someFunctionName);
    }

3 Comments

@epascarello: I haven't used it ever in production code, so I don't know how evil it can be. But, if many wise people tried it and say it is, then I go with them :)
if people say jump off a bridge because it is the quickest way down would you do it? :) Eval is slow, eval can lead to security issues, and there are better solutions.
@epascarello: I won't. I certainly don't want to re-invent the wheel, I learn from other's experience as well, otherwise you will never move forward than where others have landed in the past. I take suggestions if they make sense to me :). Also I clearly stated in my answer that eval is deprecated.
0

write something like

function test(callback1) {
    eval(callback1 + "()");
}

then callback1 should be a string

2 Comments

I know. But the pragmatic developer may always prefer evil to another 3hrs of searching :)
Pragmatic programmer should also educate followers by doing research, which isn't so hard here. Eval is like SQL parametrized by concatenated strings. I wouldn't call one a programmer when using them.

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.