Can you Create Object ?
Published: 2023-05-30 21:05:47
Can you Create Object ?
Different Methods of Creating Objects in JavaScript
Assalamu Alaikum.
JavaScript is an efficient language that is one of the most widely used programming languages in the world. And in JavaScript, object is a fundamental and important property, as it allows you to organize your data. There are several types of methods for creating an object. In this blog, I am going to discuss the methods. Let’s jump into it:
Object Literal:
The most common use of object creation is in object literals. With this method, you can create and define an object using just curly braces.
const person = {
name: 'John',
age: 30,
isStudent : true
};
This approach is straightforward and suitable for creating individual objects with specific properties and methods.
Constructor Functions:
You can create objects using the constructor function. In a constructor function, you can call the “new” keyword to create an instance of the object.
function Person(name, age, isStudent) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
}
//create object instance using new
const person = new Person('John', 30, true);
Constructor functions are useful when you need to create multiple instances with similar properties and behaviors.
Object.create():
The Object.create() method allows you to create an object with a specified prototype object. It provides more control over object instances.
javascriptCopy code
const personPrototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const person = Object.create(personPrototype);
person.name = 'John';
person.greet()
// Hello, my name is Jhon.
This approach separates the object creation and property assignment steps. kind of efficient approach.
Using Classes:
JavaScript, after the introduction of ES6, has a class syntax through which we can use the object-oriented programming features in JavaScript like most of the other languages.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('John', 30);
Class syntax provides a clear view of OOP in JavaScript.
Conclusion:
Finally, JavaScript has a variety of object creation methods that are efficient in different ways according to their use scope.
Let me know in the comment, which one you use most? 🙂
Happy coding! Allah Hafez.
objectsjavascript
Published: 2023-05-30 21:05:47