what are constructor functions in javascript

What are Constructor Functions in Javascript and The Best 15 Examples?

What are Constructor Functions in Javascript? The Javascript constructor function is one of the key concepts in JavaScript and object-oriented programming. In this article from Thinkwriteway.com, we intend to fully familiarize ourselves with this concept and its application.

First, we review the constructor definition and see how a constructor function is constructed. Then we will examine how to call Constructor functions and their types with practical examples. Next, we will get to know the difference between constructor and class in JavaScript.

Finally, we will summarize the key points. So, stay with us to improve your knowledge in the field of Constructor functions in JavaScript.

Constructor functions in JavaScript are solutions used to create and initialize “object” (Object), which enable the definition of properties and methods, thereby enhancing the reusability of program codes. Moreover, “instances” (Instances) are brought into existence through constructors and play a vital role in object-oriented programming.

So, what are constructor functions in JavaScript? The “Thinkwriteway Technology Blog” features an article delving into the concept of constructor functions in JavaScript, presented in straightforward language alongside tangible illustrations. Gaining a comprehension of Constructors in JavaScript empowers programmers to more effectively tackle coding challenges, particularly when employing an object-oriented programming approach.

What are Constructor Functions in Javascript?

Constructor function in JavaScript as a kind of normal function is the basis for building objects. For example, if a civil engineer wants to build an apartment complex that includes several buildings, to build this complex, he first provides a detailed plan of the project and then assigns the work to other people involved in the project, such as contractors, workers, etc.

In this project, if all apartment units have the same shape, only this map is used, and in this case, each apartment (object) will be built based on the provided map (constructor function). Finally, a collection of several apartments emerges, all using the same basic plan.

What are constructor functions in javascript

The key advantage of this method is the ability to repeat the design and create an array of 20, 500, 100, or more similar objects with distinct characteristics. The constructor function in JavaScript allows the user to create the object framework only once and then use this framework to create similar objects. Constructor functions play an important role in creating objects in JavaScript and act as templates for creating multiple entities that share the same properties and methods while holding diverse values.

An example of a Javascript Constructor in the real world

It is assumed that a developer is building some kind of social media website. The developer should know what information they intend to collect. To do this, the developer creates something like a form for each user to get the necessary information from the users. To illustrate this process, consider the following scenarios:

  • The same user information: In the registration of each user, it is necessary to collect a set of user information such as name, surname, age, etc. As a result, objects designed to collect data from diverse users share similar characteristics.
  • Considering the scale: it is assumed that thousands of people interact with this social network platform daily. To scale with this volume of users, multiple objects must be created to effectively manage and process each user’s distinct data.

In the above scenario, the Constructor in JavaScript is the scheme or pattern used to create new objects that will be required for each user who registers on the platform, and by using it with much less coding, the user-developer can achieve his goal of collecting information in this scenario. It is obtained from users.

Creating Javascript Constructor functions

Creating constructor functions is similar to creating regular JavaScript functions. Below is an example to illustrate this. Imagine, as above, a developer is building some kind of social media site and wants to collect information from users. For this purpose, the person developing a special function named User creates a user name that contains three things: the user’s first name, last name, and age. This function helps him to create different user profiles. The following code snippet illustrates this:

function User(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}

In the code above, a function named User It works like a blueprint. This feature allows a developer to create a large number of new user profiles for their social media site. Regarding the Constructor in JavaScript, it is important to pay attention to the following two points:

  • It is better to start the constructor function with a capital letter. Doing this is not mandatory, but it helps the user to separate constructor functions from normal functions.
  • This keyword is used a lot in JavaScript when working with constructor functions in JavaScript . This keyword is used to refer to a user-created object.
What are constructor functions in javascript

This keyword in JavaScript

This keyword in JavaScript refers to some kind of object, but which object it will refer to depends on where it is used. To better understand this issue, it is important to pay attention to the following 3 points:

  • Inside object: When the named keyword is used inside an object, this refers to that particular object.
  • In global scope: if used outside any specific object, such as the main part of the code, this Refers to a larger context, usually including the entire web page or global environment.
  • In constructor functions or classes: When this keyword is placed inside a specific function that creates objects (constructor function or class), this It represents a specific object that is created at that moment.

Simply put, the keyword helps the user to add details or actions to various objects. For example, when creating many similar objects, such as the user profile in the example above, the programmer does not want to give each object a unique name. Instead, from this Used to customize and build each object separately. So, this Is like a tool that allows the user to add special features to objects, especially if the objects are all built from the same blueprint.

Calling the JavaScript constructor function

To use the Constructor function in JavaScript, from the keyword New It is used with actual data provided, as the following example illustrates:

let user1 = new User("John", "Doe", 23);

In the code above, a specific object (instance) of the constructor User is produced, which includes the following three components:

Firstname as 'John'
Lastname as 'Doe'
Age as 23.

key word New An operator for creating new objects is a constructor function. When the keyword New Used with a constructor function, it does the following:

  • Creates a new, empty object.
  • The prototype instantiates this new object and binds it to the prototype property of the constructor function.
  • The keyword this Sets the constructor function to point to the newly created object.
  • key word New Causes the constructor function to return the new object.

In the example below, a function called newClone Operator behavior New imitates:


//This function mimics the new operator
function newClone(ConstFunction, ...theArgs) {
  
    //1. Creates a new empty object
  let obj = {};
 
  //2. Sets prototype of newly created object and links to it to prototype  property of constructor function.
  Object.setPrototypeOf(obj, ConstFunction.prototype)
 
  //3. calls the ConstFunction using `call` and sets the new object (obj) as its 'this' keyword.
  let ret = ConstFunction.call(obj, ...theArgs)
  
  //4. if it returns Object then returns it as it is
  if (ret == Object) return ret
 
  //else return obj
  return obj;
}
 
//Person created using the NewClone
const userClone  = newClone(User, 'John', 'Doe', 23)
console.log(userClone );
 
//Person created using the new operator
const user1 = new User('John', 'Doe', 23)
console.log(user1);

Both objects newClone And user1 have the same result:

{
"firstName": "John",
"lastName": "Doe"
 age: 23
}

Add methods to constructors

When using constructor functions in JavaScript, in addition to adding basic details to objects, you can do more and add methods to constructor functions. There are two methods for placing methods in constructor functions, which are discussed below.

1. Inside the Javascript Constructor

You can create the method directly in the constructor function. For example, in the constructor User, can be called a method speak As in the following example, he added:

function User(firstName, lastName, age){
    
    // defined properties
    
    //Adding method
    this.speak = function() {
        console.log("Hello! My name is " + this.firstName + " " + this.lastName + " and I'm " + this.age)+" years old.";
    }
}

2. Using prototypes

Another way to add methods to constructor functions in JavaScript is to use prototypes. This approach is a special way to share methods among all objects created from a constructor. For example, a method called getFullName Using prototypes, added the User constructor as in the following example:

function User(firstName, lastName, age){
    
    // defined properties  
}

User.prototype.getFullName = function() {
    console.log(this.firstName + " " + this.lastName);
}
 
user1 = new User("John", "Doe", 23);
user1.getFullName() // John Doe

By adding methods through prototypes, all objects are created from the constructor User They can use the new method, which is a way to make the same action available to all similar objects.

What are Constructor Functions in JavaScript and its Types

There are two main types of constructor functions in JavaScript, which include user-defined constructor functions and built-in constructor functions. Each of these functions has its own uses and can be used in different scenarios. What are constructor functions in JavaScript? Below are descriptions of each type of constructor function in JavaScript.

1. User-defined constructor functions

User-defined constructor functions are functions that developers create and define for their specific needs in the application. The constructor function we talked about earlier falls into this category. These functions were originally designed by developers to be used in their code.

2. Built-in constructor functions

JavaScript provides built-in constructor functions for each primitive data type, such as String, Number, Boolean, and Object . For example, the following code snippet shows some examples of built-in constructor functions in JavaScript:

const str = new String("string") //A new string object.
const num = new Number(56) //A a number object.
const bool = new Boolean(true) //A new boolean object.
const arr = new Array([23,32]) //A new JavaScript array.
const obj = new Object({"name":"Joe"}) //A new JavaScript object.

//Display types
console.log(typeof str) //object
console.log(typeof num) //object
console.log(typeof bool) //object
console.log(typeof arr) //object
console.log(typeof obj) //object

After executing the above code snippet, we will notice that each of them returned an object as output. This is because all JavaScript constructors return objects. Although JavaScript has special objects that can be used as numbers, strings, etc., the use of these objects can affect the performance of the user program. Primitive data type values ​​are usually faster and more efficient for most common applications.

Object prototypes in JavaScript

JavaScript is a dynamic language that allows the user to add new features to objects at any time and place. The following example illustrates this:

function Person() {
    this.name = 'John Doe';
    this.occupation = 'Developer';
}

const person1 = new Person();
person1.age = 34;
console.log(person1.age); // 34

const person2 = new Person();
console.log(person2.age); // undefined

In the code above, the attribute age is Only in the object person1 There is, no person2 because only person1 is Added. But how do you add new properties after the constructor function is defined and make them available to all instances of the object? The answer to this question lies in something called “prototype” in JavaScript .

In JavaScript, every function is associated with a special component called “Protoype”. The prototype is initially an empty object inside the function and remains inactive until the function is used as a constructor. The prototype property of the Constructor function in JavaScript serves as the prototype for all objects created from that function. It is very important to pay attention to the following example and its result in this regard:

function Person() {
    this.name = 'John Doe';
    this.occupation = 'Developer';
}

const person1 = new Person();
person1.age = 34;
console.log(person1.age); // 34

const person2 = new Person();
console.log(person2.age); // undefined

As can be seen in the results, both object instances are created from the constructor Person Now they can go to the feature age that in the manufacturer’s prototype Person They are supposed to have access. This prototyping approach enables common features across instances.

The difference between constructed objects and real objects in JavaScript

There are two approaches to creating objects in JavaScript, which include “object literals” (meaning real objects) and constructors. The approach of literal objects involves the direct definition of object properties and values. For example, the following code takes the details of 3 students. For the first student, it should be done as follows:

const student1 = {
    firstName: "Jermaine",
    lastName: "Cole",
    age: 32
}

For the knowledge of the second training, it is as follows:

const student2 = {
    firstName: "Kendrick",
    lastName: "Lamar",
    age: 24
}

For the third student, it is as follows:

const student3 = {
    firstName: "Jake",
    lastName: "Williams",
    age: 36
}

A faster way to build an object student There is. Instead of manually creating each object student A constructor can be used using a real object. It involves designing a function that serves as a blueprint for producing any number of objects the student acts Basically, the second method is to use the constructive functions approach. The first method is less efficient, especially in scenarios where there are multiple objects, and the second method has solved this problem to some extent. In this method, instead of repeating the details, you can use the template or Constructor function in JavaScript to generate objects. The following is an example to illustrate this point:

function Student(firstName,lastName,age) = {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
}

const student1 = new Student("Jermaine", "Cole", 23);
const student2 = new Student("Kendrick", "Lamar", 32);
const student3 = new Student("Jake", "Williams", 36);

The difference between the above two approaches lies in their effectiveness. The real objects approach requires specifying an additional type for each object, while the constructor functions approach involves pattern-oriented functional design in order to simplify the process of generating multiple objects. In principle, when the user is dealing with a single object with specific properties, using the real objects approach is a more appropriate choice. Meanwhile, when dealing with large collections of objects that each have similar properties, Constructor functions are a better choice in JavaScript. This approach is not only faster, but also improves code organization.

What are constructor functions in javascript

Difference between Class and Constructor in JavaScript

JavaScript stands out among other object-oriented programming languages ​​because of its unique approach that relies on constructors and prototypes instead of classes. In fact, for a significant period in JavaScript, there wasn’t even such a thing as a class. The introduction of JavaScript classes in “ECMAScript 2015” did not bring any new features to the language itself. Instead, classes serve as a form of “syntactic sugar”. They act in the sense of “readable and easy code” (Syntactic Sugar) and simplify the readability and writing of the code on the existing javascript Constructor functions.

javascript Constructor classes and functions in JavaScript are related and have similarities in how they work and what they achieve. While they may use different syntax and have some differences, they serve the same basic purpose of creating objects and defining their properties and behavior. To define a JavaScript class, from the keyword class The following example illustrates this:

class Person {
  constructor(name) {
    this.name = name;
  }
}
// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');

Inside the class declaration, you can have a method called Constructor() which has the same function as the constructor function. This javascript constructor method takes care of assigning properties in the class. The existence of the method Constructor() In the class declaration it will emphasize the fact that JavaScript classes are basically built on constructor functions.

Conclusion

javascript constructor function serves as a blueprint for creating objects with predefined properties and methods. What are constructor functions in JavaScript? These functions will provide a structured approach to efficient object instantiation. Whether using regular constructor functions or class-oriented syntax, constructors enhance code organization and reusability. javascript constructor learning, enabled by comprehending what constructor functions are in JavaScript, enables developers to efficiently manage and manipulate objects. This understanding helps create more robust and highly maintainable applications by leveraging the full potential of JavaScript’s object-oriented programming capabilities.

In the above article from the thinkwriteway technology blog, javascript constructor functions and how they work were presented in simple language and in the form of examples. Also, the way to create and call these functions, their types, their differences with prototypes, and their differences with classes were also investigated. I hope that the above article has satisfied the users of the technology blog.

If you seek further information about What are Constructor Functions in Javascript and the Best 15 Examples? or have any inquiries regarding our blog, please don’t hesitate to contact us via email at info@thinkwriteway.com

Share This Article :

Leave a Comment

What to read next