If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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'
.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.