JS: Constructor
What is a Constructor
Constructor is meant to create a object that is specific to certain type of data. (e.g. create a date object, array object, etc.)
In practice, when a function is designed to be called with the
Operator “new”
, the function f is called constructor.
(There are some exceptions.
For example, the constructor Symbol
cannot be called with new
〔see Symbol Tutorial〕)
Constructor is one of the way to create object. 〔see Create Object〕
Builtin Constructors
The most common use of Operator “new” is to create a builtin object instance, such as Date object.
const x = new Date();
Here is example of standard builtin constructors.
Construtor | Literal Expression | Constructor Syntax |
---|---|---|
Object | {properties} | new Object(args) |
Array | [items] | new Array(args) |
RegExp | /pattern/flag | new RegExp(args) |
Date | none | new Date(args) |
There are many more constructors. Builtin objects almost always have a constructor. 〔see JavaScript Object Reference〕
Primitive Value Wrapper Constructors
The following are constructors for
Primitive Value
's wrapper objects.
(when you call a method on a primitive value, such as "a,b".split(",")
, the string is temporarily converted to a string object.
That's why it has methods.)
User Defined Constructor
Two common ways to define your own constructor:
- Use the keyword
class
. 〔see Class〕 - Create a function using the
function
keyword. Make sure the function does not have return statement. 〔see Operator “new”〕
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. new F()
and
new F
are equivalent.
Do Not Confuse with Property Name “constructor”
Do not confuse constructor with property key "constructor"
.
💡 TIP: Use Literal Expression When Possible
For builtin objects, you should use the literal expression to create object whenever possible. Because:
- The constructor functions are often very complex, involves many arguments. Arg type and number of args may change its behavior.
- Some constructor can be called with Operator “new”, some not. e.g. the Symbol constructor cannot. 〔see Symbol Tutorial〕
- For some constructors, the behavior of calling it with
new
or without, is the same. For example, {Object, Array, Function, RegExp } are like that, but not Date.
💡 TIP: Constructor Name Start with Capital Letter
By convention, functions designed to be used as constructor starts with a capital letter.
JavaScript, Constructor, Class
- JS: this Binding
- JS: What is Constructor
- JS: Property Key "prototype"
- JS: Operator “new”
- JS: instanceof Operator
- JS: Property Key "constructor"
- JS: Difference Between typeof, instanceof, constructor property
- JS: Class
- JS: Class Syntax
- JS: Class Expression
- JS: typeof Class
- JS: Keyword “static” (static method)
- JS: Keyword “extends”
- JS: Keyword “super”
- JS: Define a Class Without Using Keyword class