β‘ 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}`)
}
}
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 propertiesname
andage
for each instance of thePerson
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);
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)] }
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
β‘ 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)
Mindblowing content