views:

113

answers:

3

I would like to check if a class type is even instantiable before attempting to instantiate it via the new keyword in javascript.

For example

var geocoder = new GClientGeocoder();
will fail if the GClientGeocoder class is not available in the namespace.

What's the javascript idiomatic way to do this?

A: 
function classExists(c) { 
    return typeof(c) === "function" && 
           typeof(c.prototype) === "object") ? true : false; 
}
Darin Dimitrov
+2  A: 

Hey,

You should be able to do:

if (!!GClientEncoder)

or:

if (typeof(GClientEncoder) !== "undefined")

Brian
Did you mean GClientGeocoder?
Shaun F
:-) I used the Google API and I constantly do that... yes, that's what I meant.
Brian
+2  A: 

In JavaScript any function can be a constructor. That means that you can't assume that function is a "Class". You can try to check the type, surround instantiation with try/catch block and check the return value, but not more then that. Even then, you can't predict that function is not just new (function(){});

nemisj