How To Know If A Function Is A Class Or A Function
Solution 1:
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 instanceofFunction; // true
An instanciated function will be an instance of that specific function:
var b = newa();
b instanceofFunction; // false
b instanceof a; // true
Solution 2:
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:
Solution 3:
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. Bound functions and functions constructed using arrow notation (ES6) even don't have a prototype at all.
functionisFunc(fn) {
returntypeof fn == "function" && (!fn.prototype || !Object.keys(fn.prototype).length);
}
1: not detecting atypical classes that don't make use of prototypical inheritance
Post a Comment for "How To Know If A Function Is A Class Or A Function"