New operator is used to initialize objects and create a new instance of the object.
You would have seen new
used in the object context in an earlier post. The usage is something like the below -
|
|
worldExists
is an object that has a value of type ‘boolean’. Refer the post linked above to know the difference.
Since everything (almost) is an object, new
works very similarly in its use cases.
|
|
This creates an instance of Date, which by default initializes with today’s date.
The logic extends to functions as well.
|
|
Here, new
creates the new instance, passes the variables to function, initiates variables using this
context and assigns the newly created object to f1
.
Javascript does not have ‘true’ classes - the function definition is treated as a prototype. The variables passed while creating the object is passed to constructor, bound to this
within the function, and either the return
variable or this
itself is returned.
If you are left wondering on shared variables similar to a class -
|
|
If you are now left wondering just why you should create an object rather than using the function directly, you would have to hold your breath till another day.
No.. no.. Don’t hold your breath - I was kidding. Just Google it.