Here is an object for a person who has 3 properties.
new keyword. Example
- Numbers can be made object using the
- Boolean can be made object using the
- Strings can be made object using the
- An array is an object
- A function is an object
- Date is an object
- Regex (Regular Expression) is an object
- Maths is an object
- Objects are always objects
Properties are added to the object in form of key-value pair, the key should be a string and value could be any data type.
Here, the object person has three properties:
First, create the constructor function with or without arguments and define your properties and method.
Here is how to create an object using a constructor function.
The Object.create() method is used to create a new object, using an existing object as a prototype of the newly created object.
Using this method all the properties that are created referring to older objects, has to be given value in a new object.
See in the example 'firstname' and 'lastname' of 'newPerson' in the example is given manually.
- dot notation (.): The properties of the objects are accessed using the dot operator. Example: objectname.property_name
- Array notation (): The properties of the objects are accessed using the square bracket operator. Example: objectname["property_name"]
object methods are the functions that are defined inside the object and operate on it to perform a certain task.
object method is part of the object in the form of a key-value pair.
To access the object method write method name followed by object name connected with a dot. Here is an example:
Check Working example.
Apart from a single object, you can also create an array of objects, and to access the properties of these objects you can simply loop through the array.
Consider an example of an array of students, where each student is an object itself having properties 'name', 'roll_no' and 'marks'.
Now let there be 5 students in the class, so you simply add all student object in an array and loop through the array to get desired property.
this refers to the object which is holding the function.
In the example below the sum is a method in 'number' object which is using
this keyword to access properties of its parent element.