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

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