JavaScript: What is Constructor
What is a Constructor
Constructor is meant to creat a object that is specific to certain type of data. (for example, create a date object, array object, etc.)
In practice, when a function is designed to be called with the
Operator “new”
, e.g. new f(args)
, the function f is called constructor.
(There are some exceptions.
For example, the constructor Symbol
cannot be called with new
[see Symbol Tutorial])
JavaScript spec defines constructor to be a function that creates and initializes objects. Quote:
function object that creates and initializes objects
NOTE The value of a constructor's prototype property is a prototype object that is used to implement inheritance and shared properties.
ECMAScript 2015 §Overview#sec-constructor
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. For example, 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.