Classes are indeed functions, and functions are also objects - you can put arbitrary key-value pairs onto functions, just like onto objects.
class X{}
console.log(typeof X);
console.log(X instanceof Object);
That's a class declaration. A class expression is like:
const TheX = class X{}
console.log(typeof TheX);
console.log(TheX instanceof Object);
When a class has key-value pairs directly on it (like an object), the properties are generally called "static":
class X{
static prop = 'foo';
}
console.log(X.hasOwnProperty('prop'));
Classes created with class
can't be invoked without new
, but classes created with function
can (in which case it's equivalent to a standard function).
function X() {
}
// As a class:
const x = new X();
// As an ordinary function:
const somethingElse = X();
With function
syntax, whether the function behaves as a class or as a plain function is determined by the caller - by whether new
is used or not. If new
is used, this
inside the function is set to be an object inheriting from X.prototype
, which is automatically returned at the end. If new
isn't used, this
inside the function is set to the calling context if there is one (eg someObj.X()
will have this
be someObj
).