Object literals are only the beginning
- Object Literals
- New Keyword
Object literal property values can be of any data type, including array literals, function literals, and nested object literals.
Shorthand property names
Consider a scenario in which you have to put different variables inside an object. One way of doing it is:
With ECMAScript 2015, a shorter notation is available to achieve the same thing:
Duplicated property names
If you use the same name for two properties, the second property will overwrite the first.
Object constructor creates an object wrapper for a given value. If the value is
undefined, it will create and return an empty object. Otherwise, it will return an object of a type that corresponds to the given value.
Objects can also be created using the
new creates an empty object; or, this keyword can be used with a user-defined constructor function:
with builtin Object Constructor.
To get started, first take a look at this example:
The next step is to add properties and methods to this empty object. This can be achieved with simple dot notation:
However, this practice is not recommended, as there is a scope resolution behind the scenes to check if the constructor function is built-in or user-defined.
User-defined constructor functions
Generally, this method is preferred over the object constructor. Imagine you have to create hundreds of objects with the same properties; with the object constructor method you’ll have to manually add all the properties to all the objects but with function constructor, these properties can be predefined.
Using the same function constructor, any number of objects can be created.
Using ES6 Classes to Create Objects
This method is a lot similar to using
new with the user-defined function constructor. Classes are the primary components of Object Oriented Programming (OOP). Many instances of classes can be created which are in fact objects. The constructor functions can now be replaced by classes, as they are supported in ES6 specifications
Here I have defined all the arguments inside the constructor.
Methods can be a part of the class while declarations can be added later to the created instance of the class, “objects”:
Here this method is a part of the object and will not affect our original class.