JavaScript new Keyword
While creating JavaScript objects, we use the new keyword, which creates a unique instance of the prototype for us. What if we do not use the new keyword and directly create objects? This article explains in detail the role of the new keyword in creating instances.
Syntax
Parameters
- className: The new keyword is followed by the name of the class/prototype for which we want to create an instance.
- ListOfArguments: Inside the parenthesis, we pass the list of arguments to the constructor function defined inside the prototype.
Example
Description
- The new keyword first creates a new empty object.
- Then, it binds the newly created object to the prototype of the constructing function.
- The new keyword in JavaScript takes care of the this keyword. We know that whenever there is a regular call of a function, the this keyword always points towards the global scope to find its value. Using the new keyword shifts the focus from global scope to the inside of this newly created object, giving us the correct output. The screenshot below demonstrates the same Therefore, the new keyword in JavaScript binds the data variables and data functions defined inside the constructing function.
- Finally, it returns the newly created object.
More Examples
1. Object Type and Object Instance
Suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:
Now you can create an object called myBike as follows:
2. Object Property That is Itself Another Object
Suppose you define an object called Boy as follows:
And then instantiate two new Boys objects as follows:
Then you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:
To instantiate the new objects, you then use the following:
3. Using 'new' with Classes
Browser Compatibility
Most modern web browsers, like Chrome, Edge, Firefox, Internet Explorer, etc., fully support the new keyword in JavaScript. The complete table of browser compatibility can be seen below.
Conclusion
- The new keyword is used to create a new and unique instance whenever it is used.
- It binds this to the newly created instance, which by default looks in the global window for its value and gives wrong and unexpected outputs.
- new binds Data Variables, Data Functions, and [[Prototype]] functions to the object created.
- Every object instance created has its own copy of these three things. Hence, variables and functions can be easily accessed using the (.) operator.