Question

Basically i am trying to check if a function exist dynamically..

This is my code:

var somevar = 'somefunction';

if(typeof somevar === 'function'){
    somefunction();
}

function somefunction(){
   alert('something');
}

The above code doesn't work

Is there a way to achieve what i am trying to accomplish ?

Was it helpful?

Solution

try this :

var somevar = 'somefunction';

if(typeof eval(somevar) === 'function'){
    //somefunction();
    eval(somevar+'()');
}

function somefunction(){
   alert('something');
}

OTHER TIPS

If the function is global, you can check via;

if (typeof window[somevar] === "function") {

}

Otherwise, you're just checking the type of the variable "somevar" (which, in this case, in a string).

If it isn't global, but exists on some object, you can replace window in the above example with the name of the object the potential function exists on. If it's just a function by itself in a non-global scope, you're out of luck.

some kind of jsfiddle

var somevar = 'somefunction';

if(isFunction(eval(somevar))){
    eval(somevar+'()');
}

function somefunction(){
   alert('something');
}

function isFunction(x){
    return Object.prototype.toString.call(x) === "[object Function]";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top