0

I have a popup system in my project. With a name, for example 'addnews', it knows which popup content to add and which script is necessary to handle the form. Up until now after completion I always did the same thing. Now, in some cases, I want to do something different.

Now I want to add a JavaScript function with that same name, like previous example 'addnews()', and check if that function exist. If it does run it, else do the standard things. (1)

Also executing a function with that name as variable doesn't seem to work. (2)

var functionName = 'addnews';

if (typeof functionName == 'function') { // (1) typeof functionName = string
    window[functionName](); // (2) this doesn't work for me
} else {
    // Do something standard
}

function addnews() {
    // Do something special
}
1
  • I'm not quite sure what you are trying to achieve. Why do you have to test whether a function exists? What is the overal problem you are trying to solve? "Up until now after completion I always did the same thing. Now, in some cases, I want to do something different." I guess that's your core problem, but in order to help you properly, you have to elaborate on this. Commented Feb 10, 2013 at 0:13

2 Answers 2

3

If you use this code in a document and it is not loaded complitelly your code will not find the function addnews() because it is not declare before this code.

Like in the comments: you need to use

if (typeof window[functionName] == 'function') 
Sign up to request clarification or add additional context in comments.

3 Comments

do you know his complete code? :) i use this code in some projects too and it works fine.
typeof functionName is always a string.
yes your are right. but eval = evil :) your should use if (typeof window[functionName] == 'function')
0

This will do it:

if (typeof eval(functionName) == 'function') { 
    eval(functionName+'()');
} else {
    // Do something standard
}

Update: Only use this if the answer of Mic doesnt work (whyever). Like he said eval is pretty dangerous.

1 Comment

eval is only dangerous when the input can potentially come from a different source than the user or the website itself (e.g. input from other users). Apart from potentially being dangerous, using it just leads to harder to maintain code and (possibly unnecessary) performance overhead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.