JavaScript Object

Description

JavaScript is not a full-blown object oriented programming language, such as Java, but it is designed on a simple object-based model. An object is a construct with properties that contain JavaScript variables or other objects. An object also has functions associated with it that are known as the object's method. You can define your own object in addition to JavaScript core (such as array or math) and client side objects.

Objects and Properties

An object is a collection of properties. JavaScript object has properties associated with it. You can access the properties of an object in the following way :

objectName.propertyName

In javaScript both object name and property name are case sensitive. You can define a property by assigning it a value. Let assume that there is an object called student with three properties name, class, rollno. They have defined as follows :

student.name = "David Rayy"
student.class = "V"
student.rollno = 1

Properties and arrays in JavaScript are closely related, actually they are different interfaces to the same data structure. You can access the properties of the said student object as follows :

student.["name"] = "David Rayy"
student.["class"] = "V"
student.["rollno"] = 1

The type of the said array is known as associative array as each index element is also associated with a string value. In the following example, the object name and properties have passed as arguments in the show_obj_property function which displays the properties of the object student.

function show_obj_property(obj, obj_name)
{
  var output = ""   
 for (var i in obj)      
 result += obj_name + "." + i + " = " + obj[i] + "\n";
return output;
}

Result of the above function :

student.name = David Rayy
student.class = V
student.rollno = 1

Please Google+, Like this tutorial on FaceBook, Tweet, save it as bookmark and subscribe with our Feed. Have suggestions? comment using Disqus down this page. Thanks.


share with delicious share with facebook w3r rss  share with digg share with reddit share with stumbleupon share with twitter