JS: Constructor

By Xah Lee. Date: . Last updated: .

What is a constructor

Constructor is a function that is designed to create a object that is of specific behavior. For example, the created objects all have the same property keys, methods, and share the same parent object.

Constructor is typically called with operator new.

Example of Standard Builtin constructors

User defined constructor (class)

the most easy way to create a constructor is by keyword class.

you can also just write function and set prototype and properties yourself.

Parenthesis optional for constructor call with no args

When a function is used as a constructor and without argument, the parenthesis are optional.

e.g. equivalent:

Do not confuse with property name “constructor”

Do not confuse constructor with property key "constructor".

The operator new and constructors

Cannot be called with new

Some function cannot be called with operator new. For example, the Symbol cannot, nor BigInt. These are usually not considered as constructors.

Called without new returns primitive

For some constructors, the behavior of calling it with new or without, is not the same.

new Date() results a new date object but Date() result a string.

The following constructor have the same behavior with or without new:

Non-callable constructors

the Iterator object is considered a constructor, but is not callable.

Constructor name start with capital letter

By convention, functions designed to be used as constructor starts with a capital letter.