Skip to content
Advertisement

JavaScript – Classes are special Functions?

Coming from a Python background, I’ve read this, learning Javascript:

Classes are in fact “special functions”, and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

on dev.mozilla website..

What I understand is that :

  • Functions are objects in OOP

  • And not classes are functions.

  • And maybe classes themselves are objects. I am not sure.

Am I wrong?

Advertisement

Answer

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).

Advertisement