In JavaScript, there are several ways to create objects:
{}
. For example, we can create an object literal as follows:const person = {
name: "John Doe",
age: 30,
gender: "Male"
};
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
const john = new Person("John Doe", 30, "Male");
In this example, the Person
constructor function takes three arguments: name
, age
, and gender
. It creates a new object using the new
keyword and sets its properties based on the arguments passed to it. The resulting object is assigned to the john
variable.
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
Person.prototype = {
speak() {
console.log(`Hello, I am ${this.name}.`);
}
};
const john = new Person("John Doe", 30, "Male");
john.speak(); // Hello, I am John Doe.
In this example, we define a Person
constructor function that takes three arguments: name
, age
, and gender
. We also define a method called speak()
on the prototype of the Person
constructor function using the prototype
property. When we create a new object using the new
keyword, we can call the speak()
method on that object by accessing it through the Speak()
property of the object. The resulting object will inherit the properties and methods defined on the prototype of the constructor function.
Overall, there are several ways to create objects in JavaScript, and each method has its own advantages and disadvantages depending on the use case.