41

I am defining a class in javascript using this...

// file_a.js
function class_a() {
    this.prop1 = null;
    this.prop2 = null;
}

// file_b.js
var obj = new class_a;
// I need to check here if class_a exists

How can I do this?

Regards

2
  • 2
    Nitpicky: Classes don't exist in JavaScript :) (only objects (functions are also objects) and some primitive types) Commented Nov 30, 2010 at 13:13
  • Title can be improved Commented Sep 24, 2018 at 13:15

1 Answer 1

85
if (typeof class_a === 'function')
Sign up to request clarification or add additional context in comments.

5 Comments

This won't work when the class has not yet been defined.
@OlleHärstedt — If it hasn't yet been defined, then class_a will be undefined so typeof class_a will be the string 'undefined', so the === test will evaluate as false which is the correct answer. It works perfectly.
Correct, my fault. I had an error at a different place that confused me.
what if i have class name in string? typeof window['className'] === 'function' will always return false?
Be aware that this only works in simple cases when class_a is directly under window. This doesn't work for module1.class1 since module1 might be also undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.