JavaScript: typeof Class

By Xah Lee. Date: .

Class syntax is:

class name {}

or

const name = class {};

Class is a special function object. In many ways, it's same as function.

like function, typeof on class is "function":

console.log(typeof (class {}) === "function");

like function, parent of class is Function.prototype:

console.log(Reflect.getPrototypeOf(class {}) === Function.prototype);

like function, it has properties { length, name, prototype}. (the property name is new in ES2015.):

class Cc {}

// same properties as function
const xFuncProps = (Reflect.ownKeys(function () {}));
const xClassProps = (Reflect.ownKeys(Cc));

console.log(
  JSON.stringify(xFuncProps) === JSON.stringify(xClassProps),
);

console.log(["length", "name", "prototype"].every((x) => Cc.hasOwnProperty(x)));

like function, the value of the property key "prototype", is a new object object with a property key "constructor", by default. [see Property Key "prototype"]

class Cc {}

// like function, it has a property key "prototype"
console.log(Cc.hasOwnProperty("prototype"));

// like function, the value of this property key "prototype", is a object with property key "constructor"
console.log(
  Reflect.ownKeys(Cc.prototype),
);
// [ "constructor" ];

like function, the value of property key "constructor", is the class function itself:

class Cc {}

// the value of the property key "constructor", is Cc itself
console.log(Cc.prototype.constructor === Cc);

However, class function must be called with keyword new. It cannot be called like a function by itself.

JavaScript Constructor/Class

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc