DEV Community

Cover image for Constructor Functions in JavaScript 🤖
Manikandan K
Manikandan K

Posted on

Constructor Functions in JavaScript 🤖

⚡ Introduction:

  • Constructor functions are a fundamental aspect of Object-Oriented Programming (OOP) in JavaScript.
  • They allow us to create objects with predefined properties and methods. In this blog post, we'll explore the concept of constructor functions and how they can be used to create objects in JavaScript.
  • Simply, Constructor function as template. This template is used for creating an object.

⚡ Understanding Constructor Functions:

  • Constructor functions are special functions in JavaScript used to create and initialize objects.
  • They serve as blueprints for creating multiple instances of objects with shared properties and methods.

⚡ Exploring the Code:

Let's break down the code snippet you provided:

function Person(_name, _age) {
    this.name = _name;
    this.age = _age;
    this.greet = function () {
        console.log(`Hi, Welcome ${this.name}`)
    }
}
Enter fullscreen mode Exit fullscreen mode

Function Declaration:

  • We declare a function named Person , which serves as our constructor function.
  • It takes two parameters: _name and _age , representing the name and age of a person.

Initializing Properties:

  • Inside the constructor function, we use the this keyword to create properties name and age for each instance of the Person object.
  • The values of these properties are set based on the arguments passed to the constructor function.

Adding a Method:

We define a method named greet within the constructor function. This method allows each Person object to greet with a personalized message.

⚡ Instance Creation

const person1 = new Person('Manikandan', 25);
Enter fullscreen mode Exit fullscreen mode

Creating an Instance:

We create a new instance of the Person object using the new keyword, passing 'Manikandan' as the name and 25 as the age.

Logging the Object:

We log the person1 object to the console, which displays the properties and methods associated with it.

console.log(person1) // Person Person { name: 'Manikandan', age: 25, greet: [Function (anonymous)] }
Enter fullscreen mode Exit fullscreen mode

Invoking the Method:

We invoke the greet method on the person1 object, which logs a personalized greeting message to the console.

person1.greet(); // Hi, Welcome Manikandan
Enter fullscreen mode Exit fullscreen mode

⚡ Conclusion:

Constructor functions are essential in JavaScript for creating objects with predefined properties and methods. They provide a convenient way to structure and organize code in an Object-Oriented manner. By understanding constructor functions, you'll be better equipped to leverage the power of OOP in your JavaScript projects. Happy coding..!🧑🏻‍💻

Top comments (1)

Collapse
 
vishva123 profile image
Vishva

Mindblowing content