JavaScript is a flexible object-oriented language when it comes to syntax. We will see the different ways to instantiate objects in JavaScript.
JavaScript is an object-based language that uses prototypes rather than classes. Before we move forward, let's clarify this. JavaScript allows you to create hierarchies of objects and inherit properties and their values based on this different basis.
- Creating object with a constructor: Constructor is nothing but a function and with the help of a new keyword, the constructor function allows the creation of multiple objects of the same flavor.
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person("Sudheer");
- Using object literals: Literals are smaller and simpler ways to define objects. We simply define the property and values inside curly braces.
var object = {
name: "Samiksha",
age: 22
};
Object literal property values can be of any data type, including array, function, and nested object.
- Creating object with Object.create() method: This method creates a new object by passing the prototype object as a parameter.
var object = Object.create(null);
- Using Es6 classes: The class feature to create the objects.
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person("Samiksha");
- Singleton Pattern: Singletons are objects that only exist once. The constructor returns the same instance every time, so one can avoid accidentally creating multiple instances by repeating the call.
var object = new (function () {
this.name = "Samiksha";
})();
Top comments (1)
Thanks for sharing. I am working on javascript these days. And I was stuck in a point. After reading this I got my answer. You may see it at techai.