- 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.
- The new keyword first creates a new empty object.
- Then, it binds the newly created object to the prototype of the constructing function.
- Finally, it returns the newly created object.
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
- 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.