Using functions as class:
Explanation: A class in OOPs have two major components, certain parameters and few member functions. In this method we declare a function similar to a class, there are two parameters, name and age ( the this keyword is used to differentiate the name and age of the class to the name and age of the arguments that are being supplied.) and a method printInfo that prints the value of these parameters. We then simple create an object obj of the copyClass, initialize it and call it’s method.
Using object literals:
Literals are smaller and simpler ways to define objects. Below we instantiate an object exactly same as the previous one just with the object literal.
Explanation: This method works same along the line of the previous one but instead of bundling the parameters ( name and age ) and the method ( printInfo ) inside of a function, we bundle them in the object itself, initialize the object and simply use the methods.
Singleton using a function:
The third way presented is a combination of the other two that we already saw. We can use a function to define a singleton object.
Explanation: This is a combination of the previous two methods, we bundle the methods and parameters inside a function but don’t declare a separate function for it (Like copyClass in method 1). Instead we simple use the function structure to declare a object.
- Extract unique objects by attribute from array of objects.
- ES6 | Merge Objects
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.