JavaScript: typeof Class
Class syntax is:
class name {body}
or
const name = class {body};
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.