The only javascript constructor guide you'll ever need!
JavaScript has a number of built-in object types, such as:
Math, Date, Object, Function, Boolean, Symbol, Array, Map, Set, Promise, JSON
, etc.
We call these objects native objects.
Constructors are special functions that allow us to build instances of the above built-in native objects.
In order to use a constructor, we need to prepend it with the operator new
.
Let us create a new instance of Date
object. We should run new Date()
,.After running, we will get the following result.
Fri Feb 03 2022 20:06:21 GMT+0530
One thing to note - not all the built-in objects come with a constructor function. Ex. the Math
object
When we try to run new Math()
, we get an Uncaught TypeError
, stating that Math is not a constructror.
Let us take an example.
function Icecream(flavor) { this.flavor = flavor; this.meltIt = function() { console.log(`The ${this.flavor} icecream has melted`); } }
now, from the above code, one can build as many IceCream as they want.
let chocoIcecream = new Icecream("choco");
let vanillaIcecream = new Icecream("vanilla");
chocoIcecream; // --> Icecream {flavor: 'choco', meltIt: ƒ}
vanillaIcecream; // --> Icecream {flavor: 'vanilla', meltIt: ƒ}
In the code aboev, we just built 2 instance objects of IceCream()
type.
The most common use case of new is to use it with one of the built-in object types.