The new keyword is used to create an object from a constructor function. It automatically creates and returns a new object instance.
Objects can be created using the new keyword and a constructor function.
A function used with the new keyword is called a constructor function.
MyFunc acts as a constructor when called using new.
JavaScript provides several built-in constructor functions.
Built-in data types are internally implemented as functions.
100
The new keyword performs several operations automatically while creating an object.
The first task of the new keyword is to create a brand new empty object.
The prototype of the constructor function is linked with the newly created object.
The new keyword binds all properties and methods declared with the this keyword to the newly created object.
Properties x and name become part of the new object.
Finally, JavaScript returns the newly created object automatically.
JavaScript internally adds return this; if no return statement exists.
100
200
x comes from the object and y comes from the prototype.
Variables declared without this remain private to the function.
Only x becomes part of the object.
If a constructor returns a primitive value, the new keyword ignores it.
100
The primitive value 200 is ignored.
If a constructor returns an object, JavaScript returns that object instead of the newly created instance.
undefined
Because the constructor returns a custom object, the newly created object is discarded.
| Return Type | Behavior |
|---|---|
| Primitive Value | Ignored by new keyword |
| Object Value | Returned instead of new object |
| Feature | Description |
|---|---|
| Constructor | Creates object instances |
| Prototype | Supports inheritance |
| this Binding | Binds current object |
| Automatic Return | Returns object instance |
Which of the following is the first task performed by the new keyword?