7 Ways to Create Object in JavaScript
JavaScript is often considered a functional programming language. But there are ways by which developers use it like Object Oriented too. One of the most discussed keywords in object oriented programming is Object.
So what is Object?
Objects are the instances of a class in object oriented programming pattern. Consider first image of this blog, if you fill all the values and store it somewhere then you can say it is a Person class object.
There are mainly seven ways to create object in JavaScript:
- Using the inbuilt object constructor
var object = new Object();
2. Using Object’s create method
var object = Object.create(null);
3. Simplest of all, using object literal syntax
var object = {};
4. Using function constructor
function Person(name){
var object = {};
object.name=name;
object.age=21;
return object;
}
var object = new Person("🇮🇳 Ashish 🇮🇳");
5. Using function constructor with prototype
function Person(){}
Person.prototype.name = "🇮🇳 Ashish 🇮🇳";
var object = new Person();
6. Using ES6 Class syntax
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person("🇮🇳 Ashish 🇮🇳");
7. Using singleton pattern (Similar to #4)
var object = new function(){
this.name = "Sudheer";
}
Conclusion
Every uses their favourite ways to create object. Sometimes it also depends on your use case.