mfrachet
mfrachet

Reputation: 8932

How to know if a function is a class or a function

I'm actually trying to differentiate (in my code) functions and classes.

I need to know, in a simple console.log, if the parameter of my function is a class or a simple function.

I'm actually taking about class, not object, but really a class.

Like:

function(item){
    if(isClass(item)){
        console.log('it s a class !');
    }else{
        if(isFunc(item)){
            console.log('it s a function !');
         }
    }
}

Edit : angular 2 is able to distinguish a function and a class in his injector container class

Upvotes: 4

Views: 182

Answers (3)

Bergi
Bergi

Reputation: 665574

Constructors ("classes") are only functions. There's not much that differentiates them.

However, their usage is quite different. Classes do typically have methods and maybe even other properties on their prototype. And that's in fact how you can distinguish them.1
Bound functions and functions constructed using arrow notation (ES6) even don't have a prototype at all.

function isFunc(fn) {
    return typeof fn == "function" && (!fn.prototype || !Object.keys(fn.prototype).length);
}

1: not detecting atypical classes that don't make use of prototypical inheritance

Upvotes: 1

Srini
Srini

Reputation: 1646

There are no classes* in Javascript. Instead functions in JavaScript can act like constructors with the help of new keyword. (constructor pattern)

Objects in JavaScript directly inherit from other objects, hence we don't need classes. All we need is a way to create and extend objects.

You can use jQuery.isFunction() to check if the argument passed to isFunction() is a Javascript function object.

From the documentation:

jQuery.isFunction()

Description: Determine if the argument passed is a JavaScript function object.

EDIT: As rightly pointed out by user2867288, the statement that Javascript has no classes needs to be taken with a pinch of salt.

Read these articles for more information about the ECMAScript 6 standard:

Upvotes: 1

pstenstrm
pstenstrm

Reputation: 6489

There aren't any classes in JavaScript. Though functions can be instanciated with the new keyword.

You can check if something is a function with instanceof:

var a = function() {};

a instanceof Function; // true

An instanciated function will be an instance of that specific function:

var b = new a();

b instanceof Function; // false
b instanceof a; // true

Upvotes: 2

Related Questions