For global functions you can use this one instead of eval
suggested in one of the answers.
var global = (function (){
return this;
})();
if (typeof(global.f) != "function")
global.f = function f1_shim (){
// commonly used by polyfill libs
};
You can use global.f instanceof Function
as well, but afaik. the value of the Function
will be different in different frames, so it will work only with a single frame application properly. That's why we usually use typeof
instead. Note that in some environments there can be anomalies with typeof f
too, e.g. by MSIE 6-8 some of the functions for example alert
had "object" type.
By local functions you can use the one in the accepted answer. You can test whether the function is local or global too.
if (typeof(f) == "function")
if (global.f === f)
console.log("f is a global function");
else
console.log("f is a local function");
To answer the question, the example code is working for me without error in latest browers, so I am not sure what was the problem with it:
function something_cool(text, callback) {
alert(text);
if( callback != null ) callback();
}
Note: I would use callback !== undefined
instead of callback != null
, but they do almost the same.