Creating object with a constructor:
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 three parameters, name, maker and engine ( the this keyword is used to differentiate the name,maker,engine of the class to the name,maker,engine of the arguments that are being supplied.). We then simple create an object obj of the vehicle, initialize it and call it’s method.
Using object literals:
Literals are smaller and simpler ways to define objects.We simple define the property and values inside curly braces as shown below:
In the above code we created a simple object named car with the help of object literal,having properties like name,maker,engine.Then we make use of the property accessor methods(Dot notation,Bracket notation) to console.log the values.
Now let’s see how we can add more properties to an already defined object:
We added new property called brakesType to the above defined car object and when we console.log the entire object we get:
Methods can also be part of object while creation or can be added later like properties as shown below:
Explanation:In the above code start method was added to the car object and later called by the car.start() and also the stop method was added too after the object was already declared.
Creating object with Object.create() method:
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Using es6 classes:
- Extract unique objects by attribute from array of 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.
Improved By : immukul