Many times, variables or arrays are not sufficient to simulate real life situations. JavaScript allows you to create objects that act like real life objects. A student or a home can be an object that have many unique characteristics of their own. You can create properties and methods to your objects to make programming easier. If your object is a student, it will have properties like first name, last name, id etc and methods like calculateRank, changeAddress etc. If your object is a home, it will have properties like number of rooms, paint color, location etc and methods like calculateArea, changeOwner etc.
Create an Object
Create an Object
You can create an object like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
| varobjName = new Object(); objName.property1 = value1; objName.property2 = value2; objName.method1 = function () { line of code } |
OR
1
2
3
| varobjName= {property1:value1, property2:value2, method1: function () { lines of code} }; |
Access Object Properties and Methods
You can access properties of an object like this:
objectname.propertyname;
You can access methods of an object like this:
objectname.methodname();
Try this yourself:
But creating objects of this kind is not that useful because here also, you will have to create different objects for different students. Here comes object constructor into picture. Object constructor helps you create an object type which can be reused to meet the need of individual instance.
Try this yourself:
for/in loop
Syntax:
1
2
3
4
5
6
7
| for (variablename in objectname) { lines of code to be executed } |
The for/in loop is usually used to loop through the properties of an object. You can give any name for the variable, but the name of the object should be same as that of an already existing object which you need to loop through.
Try this yourself: