Objects in javascript
JavaScript is an "object-based language". In this scripting, there is no such term as "class".
-->Create object
- var mobilePhone = new Object();
The above line creates the empty object & Object() is called as constructor.
The above line also creates the empty object.
Find the results of the above lines in the below snippet,
Assigning members to the Object
Objects in JavaScript will be in the form of key-value pairs.
We can assign any type of value to the JavaScript without any restriction.
For example,
- var mobilePhone = new Object();
- mobilePhone.Name = "Nokia";
- mobilePhone.Model = "N-1234"
- mobilePhone.Ram = "3 GB"
- mobilePhone.IsCameraExists = true;
- mobilePhone.Cost = 3000;
In the above lines of code I have created the properties like Name, Model, Ram, IsCameraExists and Cost and also assigned the values to them. Now, the mobilePhone object is having 5 properties.
Accessing the object members
Now, if I try to access the mobilePhone.Name in the console, it will print "Nokia" as a result.
For more observe the below image,
We can also assign the properties while creating the object as shown below,
- var mobilePhone = {"Name":"Nokia","Model":"N-1234","Ram":"3 GB","Iscamera" : true,"cost":3000}
And in any case, the way of accessing will be the same as mentioned above.
mobilePhone.Name --> Returns "Nokia".
For more, observe the below image,
Note 1
We can also access the object members in the following way too.
mobilePhone["Name"] --> Results "Nokia"
Note 2
If we try to access an unknown property or member by using the object it returns the "undefined".
Ex - mobilePhone.abc --> returns "undefined"
Functions in Object
In JavaScript for an object, we are allowed to use a function as a member. Whenever we add a property, we can access the function also.
Ex,
- mobilePhone.MakeCall = function() {
- alert('Hello, making a call..')
- }
In the above line, I'm creating a member "MakeCall" for a mobilePhone object and for this member I had assigned the anonymous function with some logic.
Observe the below image for clarity