Constructor

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 198:- Constructor

In JavaScript, a constructor function is used to create objects of the same type. It is a function that is used as a blueprint for creating objects. It is called a constructor function because it is used to construct and initialize objects.

When a constructor function is called with the new keyword, it creates a new object and sets the this keyword to the newly created object. It then adds properties and methods to the new object using this. Finally, it returns the newly created object.

Here is an example of a constructor function that creates a Person object:

javascriptCopy code

function Person(firstName, lastName, age) {  this.firstName = firstName;  this.lastName = lastName;  this.age = age;    this.getFullName = function() {    return this.firstName + ' ' + this.lastName;  } } var person1 = new Person('John', 'Doe', 25); console.log(person1.getFullName()); // Output: John Doe

In the above example, we have defined a Person constructor function that takes three arguments: firstName, lastName, and age. Inside the constructor function, we have used this to add properties firstName, lastName, and age to the newly created object. We have also added a getFullName method to the object.

We have then created a new Person object using the new keyword and passed in the arguments 'John', 'Doe', and 25. This creates a new Person object with the firstName set to 'John', lastName set to 'Doe', and age set to 25.

We have then called the getFullName method on the person1 object to get the full name of the person. The output is 'John Doe'.

22. Constructors And Prototypes

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support