The Complete Rules to `new`
Explore how the new keyword works in JavaScript to create objects and bind the this keyword. Understand its implicit behavior in constructor functions, its impact on object creation, and best practices for using new in object-oriented programming.
We'll cover the following...
Javascript’s “new” Keyword Explained as Simply as Possible
Normal Function Call
To explain what new does, let’s start with just a normal function, called without new. We want to write a function that will create “person” objects. It’ll give these objects name and age properties based on parameters that it takes in.
Simple enough. We create an object, add the properties to it, and return it at the end.
new
Let’s create a function that does the same thing, but we want it to be invoked using new. This function will create the same object as the one above. Common practice is to make functions that are meant to be invoked with new start with a capital letter. These functions are also referred to as constructors.
Invoking personFn normally and invoking ...