How to find out if a function is a class or function

I am really trying to distinguish (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 really do the class, not the object, but really the class.

how

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

Edit: angular 2 can distinguish between function and class in the container class of the injector

+3
javascript
source share
3 answers

There are no classes in JavaScript. Although functions can be associated with the new keyword.

You can check if there is something with the instanceof function:

 var a = function() {}; a instanceof Function; // true 

The instantiated function will be an instance of this particular function:

 var b = new a(); b instanceof Function; // false b instanceof a; // true 
+2
source share

There are no classes * in Javascript. Instead, JavaScript functions can act as constructors using the new keyword. ( constructor pattern)

Objects in JavaScript are directly inherited from other objects, so we don’t need classes. All we need is a way to create and expand objects.

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

From the documentation :

jQuery.isFunction()

Description: Determine whether the argument was passed as an object to a JavaScript function.

EDIT: As user2867288 rightly pointed out , the statement that Javascript has no classes should be taken with a lot of salt.

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

+1
source share

Constructors ("classes") are just functions. There are not many differences.

However, their use is completely different. Classes usually have methods and possibly even other properties on the prototype . And that’s actually how you can distinguish them. one
Related functions and functions constructed using the arrow notation (ES6) do not even have a prototype at all.

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

1: do not detect atypical classes that do not use prototypal inheritance

+1
source share

All Articles