JavaScript Object Constructors _ JavaScript Constructor Function Tutorial For Beginners
Aug 29, 2023
A constructor function in JavaScript is a special type of function that is used to create objects. Constructor functions are defined using the function keyword, but they have a special syntax that distinguishes them from regular functions.
The syntax for a constructor function is as follows:
function constructorName(parameters) {
// Body of the function
}
The constructorName is the name of the constructor function. The parameters are the values that are passed to the constructor function when an object is created. The Body of the function is the code that is executed when the constructor function is called.
When a constructor function is called, it creates a new object and assigns the values of the parameters to the properties of the object. The constructor function can also set the values of properties that are not passed as parameters.
The following code defines a constructor function called Person() that creates a new object representing a person:
function Person(name, age) {
this.name = name;
this.age = age;
}
The Person() constructor function takes two parameters: the name and age of the person. The this keyword refers to the newly created object. So, the expression this.name refers to the name property of the object, and the expression this.age refers to the age property of the object.
The Person() constructor function can be used to create new objects representing people. The following code creates a new object representing a person named John Doe who is 30 years old:
const person = new Person("John Doe", 30);
The new keyword is used to create a new object from a constructor function. The Person() constructor function is called with the parameters "John Doe" and 30. The person variable is assigned the reference to the newly created object.
I hope this summary is helpful. Please let me know if you have any other questions.
Here are some additional things to keep in mind about constructor functions in JavaScript:
Constructor functions are often used to create objects that have a common set of properties and methods.
Constructor functions can be nested, meaning that a constructor function can be defined inside another constructor function.
Constructor functions can be inherited, meaning that a child constructor function can inherit the properties and methods of its parent constructor function.
Show More Show Less 