A constructor function is a special type of function that allows you to programmatically create objects.
1function User(name) {
2 this.name = name;
3 this.role = "Visitor";
4}
Constructor functions are just regular functions, except it is conventional for them to be named with uppercase letters.
And when calling the constructor functions, you must use the keyword new
, which tells JavaScript that this is a constructor function, not a regular function.
1let john = new User("John");
2
3console.log(john);
1User { name: 'John', role: 'Visitor' }
Even though we did not write a return
statement, a new object will be returned, which is then assigned to the variable john
, and you can modify it like a regular object.
1let john = new User("John");
2console.log(john);
3
4john.role = "Admin";
5console.log(john);
1User { name: 'John', role: 'Visitor' }
2User { name: 'John', role: 'Admin' }
Without the keyword new
, the function will be executed like a regular function, and undefined
will be returned.