If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In JavaScript, there are different ways to create objects. One of the ways is to use a function to create objects. In this method, we create a function that acts as a constructor and use the new
keyword to create objects.
Here is an example:
javascriptCopy code
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var person1 = new Person("John", 25, "male");
var person2 = new Person("Jane", 22, "female");
console.log(person1);
console.log(person2);
In the example above, we create a function called Person
that takes three arguments name
, age
, and gender
. Inside the function, we use the this
keyword to set properties of the object being created. Then, we create two objects person1
and person2
using the new
keyword and the Person
constructor function.
We can also add methods to the constructor function, which will be available to all objects created from the constructor. Here is an example:
javascriptCopy code
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.greet = function() {
console.log("Hi, my name is " + this.name);
};
}
var person1 = new Person("John", 25, "male");
var person2 = new Person("Jane", 22, "female");
person1.greet(); // logs "Hi, my name is John"
person2.greet(); // logs "Hi, my name is Jane"
In the example above, we add a greet
method to the Person
constructor function. The greet
method logs a message to the console with the name of the person. We can then call the greet
method on each object created from the Person
constructor.
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.