Javascript new
The new
keyword in JavaScript!
The new
keyword is used to create a new object from a constructor function. When you use new
with a constructor function, it does several things:
- Creates a new object:
new
creates a new, empty object that is a prototype of the constructor function. - Calls the constructor function:
new
calls the constructor function, passing the new object as thethis
context. - Sets the
prototype
property:new
sets theprototype
property of the new object to the prototype of the constructor function. - Returns the new object:
new
returns the new object.
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 person
and calls the Person
constructor function, passing John
and 30
as arguments. The constructor function sets the name
and age
properties on the new object, and new
returns the new object.
Why use new
?
Using new
with a constructor function has several benefits:
- Creates a new object:
new
ensures that each time you create an object, it's a brand new, independent object. - Sets up the prototype chain:
new
sets up the prototype chain for the new object, which allows you to use prototype methods and properties. - Returns the new object:
new
returns the new object, making it easy to assign it to a variable or use it in your code.
Common mistakes
Here are some common mistakes to avoid when using new
:
- Forgetting
new
: If you forget to usenew
with a constructor function, it will return the constructor function itself, rather than creating a new object. - Not using
new
with a constructor function: If you usenew
with a non-constructor function, it will throw an error.