JS: Constructor
What is a Constructor
Constructor is a function that is designed to create a object that is of specific type. (e.g. create a date object, array object, etc.)
Constructor is typically called with new (operator)
Builtin Constructors
example of standard builtin constructors.
Primitive Value Wrapper Constructors
The following are constructors for Primitive Value 's wrapper objects.
User Defined Constructor
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:
new F()
new F
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 new (operator), 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: Constructor and Class
- JS: this (binding)
- JS: Constructor
- JS: prototype (property)
- JS: new (operator)
- JS: instanceof (operator)
- JS: constructor (property)
- JS: typeof, instanceof, .constructor
- JS: class (keyword)
- JS: Class Expression
- JS: typeof Class
- JS: static (keyword)
- JS: extends (keyword)
- JS: super (keyword)
- JS: Define a Class Without class