just use typeof
.
typeof(foobar) // -> undefined
typeof(alert) // -> function
You can't, however, defined a function based on typeof, because you'd need to pass an identifier which might not exist. So if you define function isfun(sym) { return typeof(sym) }
, and then tried calling isfun(inexistent)
, your code would throw.
The fun thing about typeof
is that it's an operator, not a function. So you can use it to check a symbol that's not defined without throwing.
if you assume a function in the global scope (i.e., not within a closure), you can define a function to check it as follows:
function isfun(identifier) {
return typeof(window[identifier]) == 'function';
}
Here you pass an string for the identifier, so:
isfun('alert'); // -> true
isfun('foobar'); // -> false
closure?
Here's an example of a function defined within a closure. Here, the printed value would be false
, which is wrong.
(function closure() {
function enclosed() {}
print(isfun('enclosed'))
})()