What is a javascript class exactly?

Viewed 117

I often hear that a class A, defined with class A {...}, is just a constructor, but that doesn't seem to be the case since we can access the constructor as A.constructor. So is it the prototype? That doesn't seem to be the case either as A is different from A.constructor.prototype. And yet, A is a function: A instanceof Function evaluates to true and typeof A to 'function'.

So what is a class exactly? A thin wrapper around the constructor? Can we create a class programmatically so that it's impossible to distinguish it from a class created through the class keyword?

2 Answers

but that doesn't seem to be the case since we can access the constructor as A.constructor

A.constructor is the Function constructor (because A is a function), not the class’s constructor.

class A {}

console.log(A.constructor === Function);
console.log(A.constructor.constructor === Function);
console.log(A.constructor.constructor.constructor === Function);
// all true, etc.

console.log(typeof A);
// function

What you’ve heard - that “a class … is just a constructor” – is more or less correct, though I’d leave out the “just”. A JavaScript constructor contains everything necessary to use the language’s object-oriented features; A is a function that acts as a constructor, and objects constructed with it have the prototype A.prototype.

I think this code speaks for itself:

class A {}

a = new A();
console.log(a.__proto__.constructor === A);   // true

Related