Use Constructor Function in JavaScript

Posted by

A function used to generate new objects in JavaScript is called a constructor function. It creates new objects, which is why it is known as a constructor.

The function keyword is used to create a constructor function in JavaScript. The function name ought to be illustrative of the kind of object that it will produce. A Person object’s constructor function, for instance, might be called Person.

The code that is run when a new object is formed should be in the constructor function’s body. You can use this code to set the new object’s properties to their initial values.

A constructor function in JavaScript that generates a Person object is demonstrated here:

<script type="text/javascript">
        function Person(person_name, person_age, person_gender) {
            // assigning  parameter values to the calling object
            this.name = person_name,
                this.age = person_age,
                this.gender = person_gender,
                this.greet = function() {
                    return ('Hi' + ' ' + this.name);
                }
        }
        // creating objects
        const person1 = new Person('abhishek', 25, 'male');
        const person2 = new Person('akash', 25, 'male');
        // accessing properties
        console.log(person1.name); 
        console.log(person2.name); 
    </script>
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x