The new keyword in javascript
The new
keyword in JavaScript!
The new
keyword is used to create a new instance of an object, and it's a fundamental concept in JavaScript. When you use new
with a constructor function, it does several things:
- Creates a new object:
new
creates a new, empty object that inherits from the prototype of the constructor function. - Calls the constructor function:
new
calls the constructor function, passing the new object as thethis
context. - Sets the
this
context: Thethis
context is set to the new object, allowing the constructor function to initialize the object's properties. - Returns the new object: The
new
keyword returns the new object, which is assigned to the variable specified in thenew
expression.
Here's an example:
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person('John', 30);
console.log(person); // { name: "John", age: 30 }
In this example, new
creates a new object, calls the Person
constructor function, sets the this
context to the new object, and returns the new object, which is assigned to the person
variable.
Some important notes:
- If you don't use
new
with a constructor function, it will be called as a regular function, andthis
will refer to the global object (usuallywindow
orglobal
). - If you use
new
with a non-constructor function (i.e., a function that doesn't have aprototype
property), it will throw aTypeError
. - You can use
new
with a function that doesn't have aprototype
property, but it won't create a new object. Instead, it will call the function as a regular function.
Common use cases for new
include:
- Creating instances of objects with a constructor function
- Creating a new object with a specific prototype chain
- Creating a new object with a specific set of properties and methods