3

ok I have this small code

http://jsfiddle.net/laupkram/yJtyD/

now its not really working. I had been following all the existing questions and answers here in SO but I can't make this up.

I really want to call a function without using eval()

where i had been wrong?

2 Answers 2

4

You have a typo (imafunc/iamfunc), correct it & you can (assuming global scope);

var fn = window["iamfunc"];

if (typeof fn === 'function') {
    fn("hello world");
}
Sign up to request clarification or add additional context in comments.

6 Comments

I've made a jsfiddle of your changes, but it doesnt appear to work jsfiddle.net/yJtyD/1
Change the fiddle to no wrap (head) as it stands Fiddle wraps the code in an event handler
eval() is a last resort in cases such as this (and most others) where there is a build in mechanic you can take advantage of (the window namespace)
is it ok i filled with a lot of things the window namespace? hehe i planning to abuse it tho...
You can create your own namespaces and use them; jsfiddle.net/alexk/36Ds5
|
1

You can't execute a string directly. If the function specified by the string is defined globally you can access the function by

window[ fn ]();

So in your case this would transform your code to the following:

var fn = "imafunc";
if (typeof window[ fn ] === 'function') {
     window[ fn ]("hello world");
}

function imafunc(str) {
    alert(str);
}

If the function is defined only in another function's scope, you have to resort to eval, which has some performance disadvantages and is generally considered bad practice (see, e.g., MDN).

PS: This won't work in a jsFiddle as they use sandboxing, which is like defining imafunc() inside another function. You have to change the wrapping to use "no wrap".

1 Comment

thank you this works... i was thinking i can call the function directly by a string

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.