Function to create Objects

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 197:- Function to create Objects

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.

22. Constructors And Prototypes

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?