The “new” keyword in JavaScript is used to create an instance of an object. It creates an object with the specified type and sets its proto property to the prototype of the constructor function.
Here’s an example to demonstrate the usage of the “new” keyword in JavaScript:
function Person(name, age) {
this.name = name;
this.age = age;
}
var person1 = new Person("John Doe", 30);
console.log(person1.name); // Output: John Doe
console.log(person1.age); // Output: 30
In the example above, the Person
function is a constructor function that is used to create a new Person
object. The new
keyword creates a new instance of the Person
object and assigns it to the variable person1
. The properties name
and age
are then set to the values passed as arguments.
It is important to note that the “new” keyword changes the way a function is executed. When a function is called using the “new” keyword, it is executed in the context of the new object, and the this
keyword refers to the new object.
+ There are no comments
Add yours